Python – Checking if type == list in python


I can't figure out what's wrong with my code:

for key in tmpDict:
    print type(tmpDict[key])
        print 'this is never visible'

the output is <type 'list'> but the if statement never triggers. Can anyone spot my error here?

Best Answer

You should try using isinstance()

if isinstance(object, list):
       ## DO what you want

In your case

if isinstance(tmpDict[key], list):

To elaborate:

x = [1,2,3]
if type(x) == list():
    print "This wont work"
if type(x) == list:                  ## one of the way to see if it's list
    print "this will work"           
if type(x) == type(list()):
    print "lets see if this works"
if isinstance(x, list):              ## most preferred way to check if it's list
    print "This should work just fine"

The difference between isinstance() and type() though both seems to do the same job is that isinstance() checks for subclasses in addition, while type() doesn’t.

Related Question