Attempting purify using remove


why does this code return [4,5,4] instead of [4,4]?

def purify(list):
for item in list:
if item % 2 != 0:
return list

print purify([4,5,5,4])

FAQ: Learn Python - Practice Makes Perfect - purify
FAQ: Learn Python - Practice Makes Perfect - purify

lists can’t have empty spaces/slots, so lets say we have this list with the following indexes:

4   5   5   4
0   1   2   3

and we remove the value 5 from index 1, everything to the right of the removed item moves one space/slot to the left:

4   5   4
0   1   2

combine this with a loop (which moves from index 1 to index 2), you have your answer why successive odd/uneven numbers are not removed.

Its possible to work around this problem, but then you should question if that is wise.

Maybe there are better and easier ways to solve this exercise in the first place?


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.