index() function is acting strangely in my code

by Fl1pp   Last Updated October 10, 2019 20:26 PM

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"

Tags : python


Answers 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)
C. Lewis
C. Lewis
October 10, 2019 20:10 PM

if y != int(): checks if y is not equal to the return value of the int() function – which is 0. You need to use type() or isinstance():

if not isinstance(y, int):

isinstance() is better because it supports inheritance and subclassing, but in this example it doesn't matter.

Alec Alameddine
Alec Alameddine
October 10, 2019 20:17 PM

Related Questions


Updated February 24, 2018 05:26 AM

Updated June 20, 2017 14:26 PM

Updated December 17, 2018 14:26 PM

Updated July 28, 2017 22:26 PM

Updated May 07, 2017 08:26 AM