8/12


#1

I’m trying to remove even numbers in a list

def purify(num_list):
for num in num_list:
if num % 2 != 0:
num_list.remove(num)
return num_list

but the error says: Your function fails on purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4].
where did it go wrong?


#2

You’re looping through a list that you’re removing stuff from, the removals are going to affect the behaviour of the loop
Also, removing from anywhere except the end of a list is expensive (for large lists), so consider making a new one instead, where you simply don’t include unwanted values. Alternatively, make a copy for looping so that you’re no longer removing from the same list that you’re iterating through


#3

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