0
def remove_over_5(list):
    i=0
    for n in list:
        if n > 5:
            del list[i]
        i += 1
    return list

print(remove_over_5([1,2,3,4,5,6,7,8,9]))

This function only deletes the numbers 6 and 8. Why are 7 and 9 skipped?

Marty
  • 77
  • 4
  • 1
    Never modify a list you're iterating over. – Nathaniel Ford Jul 14 '22 at 21:31
  • This isn't 100% the same, but it's very close and has some good relevant answers. In the linked post, they're using `remove`, while you're `del`eting based on index. It's the same issue though: the index/iterator doesn't take into consideration deleted elements. In your case, think about what `i` is after a delete. It's best to create a new filtered collection in most cases. – Carcigenicate Jul 14 '22 at 21:32
  • Because you `del list[i]`, which *changes the size of the list*, and the way a `list` iterator works is it blindly increments an internal counter (index), at which point, so when you remove an index, it effectively skips the next element in the iteration. See the linked duplicate for a more fleshed out explanation, this is a common trap – juanpa.arrivillaga Jul 14 '22 at 21:40

0 Answers0