. Advertisement .
..3..
. Advertisement .
..4..
For the problem “valueerror: list.remove(x): x not in list.” I tried to fix it, but It doesn’t work and returns the result I want. Here is my program:
def manage_collide(bolts, aliens):
# Check if a bolt collides with any alien(s)
for b in bolts:
for a in aliens:
if b['rect'].colliderect(a['rect']):
for a in aliens:
a['health'] -= 1
bolts.remove(b)
if a['health'] == 0:
aliens.remove(a)
# Return bolts, aliens dictionaries
return bolts, aliens
and
ValueError: list.remove(x): x not in list
has occurred. I’ve checked the entire command line but still can’t find the mistake.
The cause: Because when you use
remove
, you must name the removed item by name rather than index, this error “value error: x is not in list” will display when the code is run.Solution: You are unable to utilize a
list.remove
, so you should usedel list[x]
to delete items. It’s OK to usedel
because we’re deleting items by their index. Usingdel
, the code will work appropriately regardless of the item’s name.To find out for sure, consult the following code:
This is due to a bug in the code. This is how your code looks simplified:
This is why
aliens
loops overaliens
multiple time for each entry inb
. This will causealiens
to loop overaliens
multiple times for every entry inb
.There are a few things you need to fix. To use
a
instead ofaliens
, first change the inner loop.Second, remove
b
only once. so:This code has other problems, but it is what is causing your problem. Martijn’s post might also be of assistance.