Python index error value not in list…on .index(value)

Python index error value not in list…on .index(value)

Lets show some equivalent code that throws the same error.

a = [[1,2],[3,4]]
b = [[2,3],[4,5]]

# Works correctly, returns 0
a.index([1,2])

# Throws error because list does not contain it
b.index([1,2])

If all you need to know is whether something is contained in a list, use the keyword in like this.

if [1,2] in a:
    pass

Alternatively, if you need the exact position but dont know if the list contains it, you can catch the error so your program does not crash.

index = None

try:
    index = b.index([0,3])
except ValueError:
    print(List does not contain value)

subset.index(currentPosition) evaluates False when currentPosition is at index 0 of subset, so your if condition fails in that case. What you want is probably:

...
if currentVal == 0 and currentPosition in subset:
...

Python index error value not in list…on .index(value)

Why complicate things

a = [[1,2],[3,4]]
val1 = [3,4]
val2 = [2,5]

check this

a.index(val1) if val1 in a else -1
a.index(val2) if val2 in a else -1

Leave a Reply

Your email address will not be published.