12/15 important question


#1

I wrote my code:

def purify(nums):
  
  for i in nums:
    if i % 2 != 0:
      nums.remove(i)
    else:
      pass
  return nums

and it returns “Your function fails on purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4].”
Then I watched the solution:

def purify(lst):
    res = []
    for ele in lst:
        if ele % 2 == 0:
            res.append(ele)
    return res

and I don’t understand the difference. I mean I wrote even easier but why my code doesn’t work??


#2

actually, your solution is more complicated. Removing from the list you are looping over gives complications, as you experienced.

lists can’t have empty spots in a list, so the moment you remove something from the list, everything to the right of the removed item will move to the left, to fill the gap created by the removed item.

this is a problem in combination with the for loop, given the loop moves to the next index.


#3

that means, that if list [2,3,5,6] comes through my code, it will remove 3, than 5 will stand at the place of 3 with its index, code will pass it and won’t delete 5?


#4

yes, after the removal of three and five being moved, the loop progresses to the next index, causing a skip


#5

I didn’t know it, thanks!


#6

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