365

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

for key in tmpDict:
    print type(tmpDict[key])
    time.sleep(1)
    if(type(tmpDict[key])==list):
        print 'this is never visible'
        break

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

4
  • 6
    Have you used list as a variable somewhere? Beware that if you're working in the REPL or such it may still be re-defined from a while ago. Commented Oct 24, 2014 at 8:24
  • 3
    .....Woooowww... definitely a lesson regarding the shortcomings of softly typed languages. Wow... Commented Oct 24, 2014 at 8:26
  • 1
    Add it as answers and I'll accept. THANKS. Commented Oct 24, 2014 at 8:27
  • 4
    Pylint and friends will help you out in the future (I wouldn't call this a shortcoming, really). Commented Oct 24, 2014 at 8:28

5 Answers 5

517

You should try using isinstance()

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

In your case

if isinstance(tmpDict[key], list):
      ## DO SOMETHING

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.

Sign up to request clarification or add additional context in comments.

Comments

212

Your issue is that you have re-defined list as a variable previously in your code. This means that when you do type(tmpDict[key])==list if will return False because they aren't equal.

That being said, you should instead use isinstance(tmpDict[key], list) when testing the type of something, this won't avoid the problem of overwriting list but is a more Pythonic way of checking the type.

1 Comment

Nice. 'more Pythonic' is a wide concept. just for the sake of education: what-are-the-differences-between-type-and-isinstance?
31

This seems to work for me:

>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True

Comments

11

Python 3.7.7

import typing
if isinstance([1, 2, 3, 4, 5] , typing.List):
    print("It is a list")

Comments

6

Although not as straightforward as isinstance(x, list) one could use as well:

this_is_a_list=[1,2,3]
if type(this_is_a_list) == type([]):
    print("This is a list!")

and I kind of like the simple cleverness of that

2 Comments

This does not work in python v3.9.15
I was struggling with list type check for a while. You saved my time!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.