The list is a direct sequence of values, they are not associated with the index. Then, when removing an element from the middle of the list, all elements in front are "shifted".
For example, if you have a list with 3 elements lista = ['a', 'b', 'c']
- The element
0
is the 'a'
(lista[0]
)
- The element
1
is the 'b'
(lista[1]
)
- The element
2
is the 'c'
(lista[2]
)
When removing the element 0
(with del lista[0]
) the list goes like this: ['b', 'c']
- The element
0
now is the 'b'
(lista[0]
)
- The element
1
now is the 'c'
(lista[1]
)
- There is no more element
2
Then you remove the element 1
(with del lista[1]
), the list goes like this: ['b']
- The element
0
now is the 'b'
(lista[0]
)
- There is no more element
1
nor 2
, the list has only one element
Finally, when trying to remove the element 2
(with del lista[2]
) you receive the error because the list no longer has the element 2
.
A common way to solve this problem is to remove the elements always ordering backwards, ie remove the element 2
first, then the 1
and finally the 0
, as this prevents the displacement of items that will be removed in the future.
When you remove position 0, the list has two values:
'a'
at position 0 and'b'
at position 1. When you remove position 1, you are removing'b'
and when you try to remove position 2, it is wrong, since at that point the list will have only'a'
at position 0.– Woss