1

I cannot figure why some numbers greater than 10 are still left. Please help. Thanks.

mylist = [12,31,2,5,45,12,45,4,32,1,6,8,5,31,12,11]

for num in mylist:
    if num >= 10:
        mylist.remove(num)

print(mylist)
emrhzc
  • 1,347
  • 11
  • 19
twicelost
  • 61
  • 8

1 Answers1

1

you are iterating a list that is being modified, so the iterator index skips to another thinking it's intact. I'd suggest another way for that goal

mylist = [number for number in mylist if number < 10]
emrhzc
  • 1,347
  • 11
  • 19
  • This is not really equivalent as it is a rebinding, and not a mutation as attempted by the OP. Better do `mylist[:] = ...`. – user2390182 Apr 27 '20 at 10:44