Checking list of types == in python

I might have a brain fart here, but I really can't figure out what happened to 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 runs. Can someone point out my mistake here?

+90
source share
3 answers

Your problem is that you redefined list as a variable earlier in your code. This means that when you do type(tmpDict[key])==list if returns False because they are not equal.

In this case, you should instead use isinstance(tmpDict[key], list) when testing the type of something, this will not eliminate the problem of rewriting list but it is a more Pythonic method of type checking.

+74
source

You should try using isinstance()

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

In your case

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

Develop:

 x = [1,2,3] if type(x) == list(): print "This wont work" if type(x) == list: ## one of the way to see if it 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 list print "This should work just fine" 
+96
source

This seems to work for me:

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

Source: https://habr.com/ru/post/1205425/


All Articles