0

let's say I am trying to delete the elements of a list in python that belong to even indexes like this:

q=int(input("cate elemente sa aibe lista?\n"))
l=[int(input()) for i in range(q)]
list_indexes=[]

#while len(l)!=1:
for i in range(len(l)):
    if i % 2 == 1:
        list_indexes.append(i)

for i in list_indexes:
    del l[i]

print (lista)

My error says that:

line 11, in <module>
    del l[i]
IndexError: list assignment index out of range

I've been trying to debug it and i shouldn't be out of range and it seems like I am repeating this mistake in other examples of code as well. Can somebody explain to me what am I doing wrong so that I won't repeat it please? I know there are simpler ways to do this exercise but I want to learn what is my mistake here.

Many thanks!

  • 1
    Why not use `del l[::2]` without any looping? – cs95 Nov 02 '20 at 11:08
  • 1
    When you delete an element the list size changes. So eventually you call `del` for an index out of range. – b-fg Nov 02 '20 at 11:09
  • 1
    Alternatively, you would iterate from the end using `for idx in reversed(range(len(lst))): if idx % 2 == 0: del lst[idx]` and remove even indices. – cs95 Nov 02 '20 at 11:11
  • @b-fg I know this might be the problem but when I test the ```list_indexes``` all of the elements in it are in the range of ```l``` so I can't see why it says it's out of range. – Petre Butunoi Nov 02 '20 at 11:17
  • 2
    Visualize it on [PythonTutor](http://pythontutor.com/visualize.html) to understand the problem. – Mr. T Nov 02 '20 at 13:21
  • 1
    @Mr.T that was actually really really helpful thanks a lot, I could visualize it much easier! – Petre Butunoi Nov 03 '20 at 12:51

0 Answers0