Reputation: 113
Im doing a mini school project, and i m getting the error e referred in the title. How do i solve my error?
This is for a mini "football manager" project and i know my error is this one line!
equipas=['Napoli','Inter','Milan','Roma','Sampdoria','Atalanta','Lazio','Fiorentina','Torino','Sassuolo','Parma','Genoa','Cagliari','SPAL','Udinese','Empoli','Bologna','Frosinone','Chievo']
for m in range(0,99):
try:
z=equipas[m]
except IndexError:
a+=1
if a==3:
break
else:
equipa=equipas[m]
equipas.remove(equipa)
pontos=random.randint(0,57)
equipa=equipa,pontos
listaequipa.append(equipa)
print(listaequipa)
When the program prints the variable listaequipa
, I only get this in the final line:
[('Napoli', 44), ('Milan', 57), ('Sampdoria', 31), ('Lazio', 14), ('Torino', 3), ('Parma', 13), ('Cagliari', 51), ('Udinese', 8), ('Bologna', 21), ('Chievo', 38)]
Upvotes: 0
Views: 62
Reputation: 236004
You should not iterate over the indexes of a list and remove elements from it at the same time. That's what's causing the error.
Fortunately you have a couple of alternatives, pick the one that you're more comfortable with:
None
) and afterwards remove all of them at the same time, using filter
or a list comprehension.Upvotes: 1
Reputation: 1227
When you remove an item from a list using
list.remove(item)
It doesn't replace the item with a null value, it removes it completely and the rest of the elements take its place. For example:
array = ['1', '2', '3', '4', '5', '6']
for x in range(5):
array.remove(array[x])
After the first pass of the loop, the array now looks like:
['2', '3', '4', '5', '6']
and then the for loop increments x
so it removes the second element in the current list:
['2', '4', '5', '6']
And so on, skipping every second value of the original list.
So read over your code, and see where this could be happening.
Hope this helps :)
Upvotes: 0