How to filter a list

python

Solution

When you remove an item, the items that follow get moved one position to the left. This results in the loop skipping some items.

BTW, a more idiomatic way to write that code is

numbers = [num for num in numbers if num % 2 == 0]

Problem

Im writing a simple function to take out any odd numbers from a list and return a list of only the even ones. ``` def purify(numbers): for i in numbers: if i%2!=0: numbers.remove(i) return numbers print(purify([4,5,5,4])) ``` However, the above returns: ``` [4, 5, 4] ``` Why doesn't the second 5 get removed as it also meets the if condition? Im looking less for a different method to the problem and more to understand why this happens.

Original source

Related problems