Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python2.7 - list.remove(item) within a loop gives unexpected behaviuor [duplicate]

I want to remove all even numbers in a list. But something confused me... This is the code.

lst = [4,4,5,5]

for i in lst:
    if i % 2 == 0:
        print i
        lst.remove(i)

print lst

It prints [4, 5, 5] Why not [5, 5]?

like image 372
Sam Avatar asked Nov 19 '25 14:11

Sam


2 Answers

It should be like this

for i in lst[:]:
    if i % 2 == 0:
        print i
        lst.remove(i)

print lst

Problem:

You are modifying the list while you iterate over it. Due to which the iteration is stopped before it could complete

Solution:

You could iterate over copy of the list

You could use list comprehension :

lst=[i for i in lst if i%2 != 0]
like image 168
The6thSense Avatar answered Nov 22 '25 02:11

The6thSense


By using list.remove, you are modifying the list during the iteration. This breaks the iteration giving you unexpected results.

One solution is to create a new list using either filter or a list comprehension:

>>> filter(lambda i: i % 2 != 0, lst)
[5, 5]
>>> [i for i in lst if i % 2 != 0]
[5, 5]

You can assign either expression to lst if needed, but you can't avoid creating a new list object with these methods.

like image 29
juanchopanza Avatar answered Nov 22 '25 04:11

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!