I'm trying to find the index of a non integer from a list, however when running the script for different values I get different indexes each time! Am I using index() not as intended? I'd appreciate any help.
m = [1, 2, '.', 3] pos = int() for y in m: if y != int(): pos = m.index(y) print(pos)
For this particular list the output prints "3", instead of the wanted "2"
You need to check the type of y and you do not need to initialize pos as an int
m = [1, 2, '.', 3] for y in m: if not isinstance(y, int): pos = m.index(y) print(pos)
if y != int(): checks if
y is not equal to the return value of the
int() function – which is 0. You need to use
if not isinstance(y, int):
isinstance() is better because it supports inheritance and subclassing, but in this example it doesn't matter.