0
del user[i] IndexError: list assignment index out of range
user = [1,2,34,45,37]

a = len(user)

for i in range(a):
      del user[i]

print(user)
PM 77-1
  • 12,933
  • 21
  • 68
  • 111

1 Answers1

0

The list user loses one element on every pass. Therefore you can't delete the 4th element after you've deleted the first three... The list is, by that point, only two elements long.

In general, you should be very careful about modifying iterables while looping over them.

Sarah Messer
  • 3,592
  • 1
  • 26
  • 43
  • ok , now what can i do? – xxxtenaction Aug 24 '22 at 10:40
  • It depends on what you _actually_ want to do once you get past the range of the minimal reproducible example you've given. This question was marked as a duplicate, and the original has several answers which can be adapted for your situation: https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it They boil down to "make a new list without modifying the original" and "choose the order of deletions to start at the end of the list" – Sarah Messer Aug 24 '22 at 16:42