Your function fails on purify([4, 1, 5, 1341, 34, 6, 8]). It returns [4, 5, 34, 6, 8] when it should return [4, 34, 6, 8].

I don’t see why it should fail. 5 should fall under the umbrella of “not even” within the code, and the code erased the other odd numbers in the list…

def purify(x):
  for item in x:
    if item != 0 and item % 2 != 0:
      while item in x:
  return x

print purify([4, 1, 5, 1341, 34, 6, 8])


problem: index shift

a list can’t have empty indexes, so the moment value 1 at index 1 is removed from the list everything to right of the removed item shifts one place/index to the left to fill the gap

then the loop progresses to the next index (2), causing the value 5 (which moved from index 2 to index 1) to be skipped


Ok…that’s interesting. So how do I work around that? Start the loop over?


one of the test cases by the exercise is [6,6,6,6,6], not sure how many 6’s where in there, but quit a lot, so that would be quit a challenge

now, i normally advise not to use .remove(), del or .pop() for this exercise, its easier to go with opposite approach (append even numbers to new list)

now, the interesting thing about index shift is that it only occurs as you remove from the same list as you are looping over, so a good solution would be to not remove from same list as you are looping over. This would require making a copy of the list


A post was split to a new topic: Purify


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