educative.io

Challenge 1: Remove Even Integers from List

def remove_even(lst):
   for index, value in enumerate(lst):
      z=abs(value)
      if z % 2 == 0:
        lst.pop(index)
   return lst

why is this not correct for challenge 1?

I have figured it out don’t mutate a list that you are looping in.

Hello @Tatenda_Zhou,

Your approach is slightly wrong. Basically, in this code, index is not updating according to the list size. For Example, 12 is placed on index 2 and 12 is an even number when you pop 12 from index 2, the size of the list changes. By this, indexes also have to be updated, but this is not happening in your solution.

Exactly, if you want to update an array, whether you are appending or poping, always use a copy of the list for that.

I hope I have answered your query. If you still have any confusion, please let us know.

Thank You :blush: