Purify - question


#1

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

Why this above code does not work?


#2

Hi @designplayer65570,

This alters lst as you are iterating through it, which interferes with the iteration …

lst.remove(a)

Instead, create a new empty list and place the even numbers into that list as they are encountered in original list during the loop. Finally, return that new list.


#3

I see. Any idea what exactly happens internally when iterating?


#4

As the first iteration begins, a counter is set to index 0. At the beginning of each subsequent iteration, it moves to the next index.

If you have the following list

[4, 3, 5, 8, 6, 2]

… and try remove odd numbers as you iterate through it, the item at index 1, namely 3, will get removed during the second iteration. During the removal, the elements following the empty position get shifted so that the empty position gets filled. As a result, the 5 will wind up at index 1.

The next iteration will visit index 2, where the 8 will have become located, and the 5 will never get processed. Consequently, it will not get removed.

After the loop has completed all its iterations, the result will be …

[4, 5, 8, 6, 2]

#5

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