0
lst = [1, 2, 3, 4, 5, 6]
for item in lst:
    if item > 3:
        lst.remove(item)

print(lst)

output: >>> [1, 2, 3, 5] How come this code doesn't produce the output of "[1, 2, 3]"? I've tried to work around this but the only way I can think of is appending the items larger than 3 to a new list. Thanks for any feedback.

rayyan
  • 1
  • 1
    Why not use a list comprehension? `lst = [item for item in lst if item <= 3]` – Barmar Feb 07 '22 at 16:46
  • 1
    You are modifying the same list you are iterating over. You can append to a new list by slicing your original one. `for item in lst[:]:` should solve this. – vaughan is god Feb 07 '22 at 16:56

0 Answers0