I wrote a function to remove odd number from a list, like that:
def remove_odd(l):
for i in l:
if i % 2 != 0:
l.remove(i)
print l
return l
remove_odd([4,5,4])
remove_odd([4,5,4,7,9,11])
remove_odd([4,5,4,7,9,11,12,13])
It returns:
[4, 4]
[4, 4, 9]
[4, 4, 9, 12]
-> wrong
but when I change to remove even number:
def remove_even(l):
for i in l:
if i % 2 == 0:
l.remove(i)
print l
return l
remove_even([4,5,4])
remove_even([4,5,4,7,9,11])
remove_even([4,5,4,7,9,11,12,13])
The answer is OK:
[5]
[5, 7, 9, 11]
[5, 7, 9, 11, 13]
What is wrong with the remove_odd() func?
I know people usually create the second list inside the func then append even number to that list, but can we solve this exercise with list.remove() ?
Thank you!
Your function is working in another way than you would expect. The
forloop takes first element, than second etc., so when you remove one element, others change their positions and can be skipped by it (and that happens in your case) when they are preceded by another odd number.If you insist on using
.remove()method, you must operate on a copy instead, like this:(
l[:]is a shallow copy of listl)However, I think using list comprehension would be much clearer: