Hey, i need help with this. I’m just wondering why it’s not working
def purify(lista):
for x in range(len(lista)): #all the way up but not including
if lista % 2 != 0: #gets an element from index
del lista # should remove that element but it is here the list index out of range
return lista occurs
i did a function, purify, it’s prupose was to remove the odd elements, somehow it didn’t work. It threw list index out of range.
I don’t understand
Doing del on an element of the list, shortens the list.
>>> L = [1,2,3]
>>> del L[1]
>>> L
[1, 3]
However, the range(len(lista)) will not know about it
>>> R = range(len(L))
>>> del L[1]
>>> L
[1]
>>> del L[0]
>>> L
[]
>>> for x in R:
... print(x)
...
0
1
and the x will eventually take values that are larger than the current size of the list. That is why it is complaining that the index went out of range.
You could create a new list, in which you insert the elements that you want to keep and then give that new list as the result.
If you want to modify the given list, you need to ask each iteration if your index x is larger (\geq) than the size.