0

I want to iterate over a list, print the elements and remove them. (I'm interested in the principle not the outcome i know i can use list.clear) I'm trying this code:

def function(list):
for i in list:
    print(i)
    list.remove(list[0])

list = [1,2,3]
function(list)
print(list)

and getting weird output:

1
3
[3]

Any thoughts?

  • Yes, see the linked duplicate – juanpa.arrivillaga Oct 08 '22 at 19:57
  • 2
    It's a basic principle not to change a list you are iterating over. Kind of like sawing through the branch you are sitting on! The loop 'remembers' how far you are through the list so if you remove an element ... – user19077881 Oct 08 '22 at 19:59
  • 2
    Also, as a side note, please try to avoid shadowing names of built-in functions, such as `list`. It can create strange and hard to debug problems in the future. – Hampus Larsson Oct 08 '22 at 20:01

0 Answers0