Python Forum
Why does modifying a list in a for loop not seem to work? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why does modifying a list in a for loop not seem to work? (/thread-19984.html)



Why does modifying a list in a for loop not seem to work? - umut3806 - Jul-22-2019

numbers = [2,8,6,12,13,9,5]
for number in numbers:
    if number % 2 == 0 :
        numbers.remove(number)
print(numbers)
I wrote that code and run it .But it should delete all the even numbers in the list. But it left some of them .Please check it and give me a solution.
Huh Huh Huh


RE: That's so strange ... - buran - Jul-22-2019

you should not modify numbers while iterating over it

numbers = [2,8,6,12,13,9,5]
odd_numbers = []
for number in numbers:
    if number % 2: # number is odd
        odd_numbers.append(number)
print(odd_numbers)
or simply
numbers = [2,8,6,12,13,9,5]
odd_numbers = [number for number in numbers if number % 2]
print(odd_numbers)



RE: Why is modifying a list in a for loop not seems to be working? - umut3806 - Jul-22-2019

Thanks