Home > Backend Development > Python Tutorial > Why Does Modifying a List During Iteration Produce Unexpected Results?

Why Does Modifying a List During Iteration Produce Unexpected Results?

Susan Sarandon
Release: 2024-12-23 19:53:17
Original
803 people have browsed it

Why Does Modifying a List During Iteration Produce Unexpected Results?

Unexpected Results While Modifying a List During Iteration

When modifying a list while iterating over it, unexpected results can occur. Consider the following code:

numbers = list(range(1, 50))

for i in numbers:
    if i < 20:
        numbers.remove(i)

print(numbers)
Copy after login

Despite the intention to remove numbers less than 20 from the list, the resulting output includes some of these numbers. This discrepancy arises because the list is being altered during iteration.

Specifically, after removing the first number below 20 (1), the loop proceeds to the next item in the original list, which is now 3 instead of 2. This process continues, resulting in the removal of all odd numbers below 20.

To avoid this issue, it's recommended to use an alternative approach, such as list comprehensions or generator expressions. Here's an example using a list comprehension:

numbers = [n for n in numbers if n >= 20]
Copy after login

This code preserves the original order of the list while filtering out unwanted elements. Alternatively, you can use in-place alteration with a generator expression:

numbers[:] = (n for n in numbers if n >= 20)
Copy after login

If you need to perform operations on an element before removing it, consider using an indexed loop and setting the element to None. Then, create a new list that includes only non-None elements:

for i, n in enumerate(numbers):
    if n < 20:
        print("do something")
        numbers[i] = None
numbers = [n for n in numbers if n is not None]
Copy after login

The above is the detailed content of Why Does Modifying a List During Iteration Produce Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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