The list is a direct sequence of values, they are not associated with the index. So by removing an element from the middle of the list, all the elements ahead are "moved".
For example, if you have a list of 3 elements lista = ['a', 'b', 'c']
- Element
0
is 'a'
( lista[0]
)
- Element
1
is 'b'
( lista[1]
)
- Element
2
is 'c'
( lista[2]
)
When you remove the element 0
(with del lista[0]
) the list looks like this: ['b', 'c']
- The element
0
is now 'b'
( lista[0]
)
- The element
1
is now 'c'
( lista[1]
)
- No more element
2
Then you remove the element 1
(with del lista[1]
), the list looks like this: ['b']
- The element
0
is now 'b'
( lista[0]
)
- There is no more element
1
nor 2
, the list has only one element
Finally, when you try to remove the element 2
(with del lista[2]
) you get the error, because the list no longer has the element 2
.
A common way to solve this problem is to remove the elements always by ordering from back to front, ie removing the element 2
first, then the 1
and finally the 0
, as this prevents the items that will still be removed in the future.