Home  >  Article  >  Backend Development  >  How to Replace List Values Conditionally in Python?

How to Replace List Values Conditionally in Python?

Susan Sarandon
Susan SarandonOriginal
2024-10-17 18:23:31758browse

How to Replace List Values Conditionally in Python?

Replacing List Values Conditionally in Python

When working with lists, it's often necessary to modify their values based on certain conditions. One common task is to replace values with None if a condition evaluates to True.

Solution Using List Comprehension

The most efficient way to do this is through a list comprehension.

<code class="python">new_items = [x if x % 2 else None for x in items]</code>

Here, items is your original list, and x % 2 checks whether the item is even. If true, it replaces the item with None; otherwise, it keeps the original value.

In-place Modification

While it's possible to modify the original list in-place, it's not recommended for efficiency reasons.

<code class="python">for index, item in enumerate(items):
    if not (item % 2):
        items[index] = None</code>

This approach requires iterating over the entire list twice, which can be costly for large lists.

Timing Comparisons

Benchmarking the two approaches shows that list comprehension is significantly faster, particularly for large lists.

Python 3.6.3:

(In-place) 1.06 µs ± 33.7 ns per loop
(List comprehension) 891 ns ± 13.6 ns per loop

Python 2.7.6:

(In-place) 1.27 µs per loop
(List comprehension) 1.14 µs per loop

The above is the detailed content of How to Replace List Values Conditionally in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn