Reputation: 1
I was given this code
lista = list(range(30))
print(lista)
for i in range(0,len(lista)):
if lista[i]%3 == 0:
del lista[i]
print(lista)
And in the if I got and error telling me that it's out of range for my list. But if the for loop is in range of the length of this list it makes no sense that the list index for every i is out of range as it can only get list length number of values?
Upvotes: 0
Views: 35
Reputation: 22023
You can't do this. If you are modifying the size of the list in a for loop and modifying its length, you won't get the result you want.
Say you can delete one element here in your list of size size
. So all of a sudden lista[size-1]
doesn't work, but you still are going to try to access it.
That's your error. the range is defined at the beginning of the call, it's not updated after each iteration.
As mauve and Asier ricardo Rafales Vila said, the solution is lista = [i for i in range(30) if i%3 != 0]
.
Upvotes: 1
Reputation: 21
You can solve the problem by adding the elements that aren't multiples of 3 to a new list ex:
lista = list(range(30))
print(lista)
new_lst = []
for i in range(0,len(lista)):
if lista[i]%3 != 0:
new_lst.append(lista[i])
print(new_lst)
Upvotes: 0