I'm doing some coding exercises and cannot understand why the code I wrote removes only some odd numbers, rather than all of them (the goal is to remove ALL odd numbers and return a list of only even numbers):
def purify(numlist):
for i in numlist:
if i % 2 != 0:
numlist.remove(i)
return numlist
print (purify([1, 3, 4, 6, 7]))
I realize there are other ways to reach a solution, but my question is why the particular code above isn't working. The list argument I passed above returns [3, 4, 6] as opposed to just [4, 6]. The remainder of 3 divided by 2 is NOT 0, so why is it not also removed? Have I perhaps used the remove method in an incorrect way? Does the phrase numlist.remove(i)
not overwrite numlist
after removing i at each iteration?