Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if type == list in python

Tags:

python

People also ask

How do you check if a type is in a list Python?

The most straightforward way to check if an object is of type list is to use Python's built-in type() function that returns the type of the object passed into it. You can then use the equality operator to compare the resulting type of the object with the list using the expression type(object) == list .

How do you find the Dtype of a list?

To check the data type of variable in Python, use the type() method. The type() is a built-in Python method that returns the class type of the argument(object) passed as a parameter. You place the variable inside a type() function, and Python returns the data type.

How do I check if a string is in a list Python?

We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1. count(s) if count > 0: print(f'{s} is present in the list for {count} times.

How do you check if an item is not in a list Python?

“not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.


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.


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.


This seems to work for me:

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

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


Python 3.7.7

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