0

I am new to Python and I tried running the below code, which defines a list and iterates through it, removing the element at index "x".

list1 = [1, 2, 3, 4, 5, 6]

for x in list1:
 
 list1.remove(x)
 
 print(list1)

However it is removing elements at even indexes only, as you can see from the visual example below:

image

How can I modify my code to make it obtain the below output?

[2, 3, 4, 5, 6]
[3, 4, 5, 6]
[4, 5, 6]
[5, 6]
[6]
[]
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70

1 Answers1

0

Never remove elements whilst you are iterating through the same list.

As the list is modified as you iterate, the iterator will correspond to an element of the list which is not what you expect anymore.

To solve it, iterate through a copy of the list, using the [:] syntax:

list1 = [1, 2, 3, 4, 5, 6]
for x in list1[:]:
  list1.remove(x)
  print(list1)
BiOS
  • 2,282
  • 3
  • 10
  • 24