How to Replace List Values Conditionally in Python?

Susan Sarandon
Release: 2024-10-17 18:23:31
Original
757 people have browsed it

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>
Copy after login

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>
Copy after login

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
Copy after login

Python 2.7.6:

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

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!