How to Check if an Object is of Type List in Python?

Rate this post

Problem Formulation: Given a Python object. How to check if the given Python object is of type list?

Example: Given a dictionary for which you don’t know the values associated to the keys. For example, suppose you have entry dict[key] for which you don’t know the type. How to check if it’s a list?

Given:    object
Goal:      True  –  –  if object is of type list
           False  –  – otherwise

Method 1: type(object) == list

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.

>>> d = {1: [1, 2, 3],
	 2: 'hello'}
>>> type(d[1]) == list
True

If you check for a non-list, the return value is False:

>>> type(d[2]) == list
False

Note that this is not the most Pythonic solution because Python is a weakly-typed language—you can redefine the name list in your code in which case it wouldn’t work as expected:

>>> d = {1: [1, 2, 3],
	 2: 'hello'}
>>> list = 42
>>> type(d[1]) == list
False

Wow! This is messy! Suddenly your dictionary element doesn’t seem to be a list anymore! Of course, it still is—the code doesn’t work simply because the name list is now associated to an integer value:

>>> type(list)
<class 'int'>

Therefore, it’s recommended to use the isinstance() built-in method instead to check if an object is of type list.

Method 2: isinstance(object, list)

The most Pythonic way to check if an object is of type list is to use Python’s built-in function isinstance(object, list) that returns either True or False.

>>> d = {1: [1, 2, 3],
	 2: 'hello'}
>>> isinstance(d[1], list)
True
>>> isinstance(d[2], list)
False

Note that if you’d overwrite the name list with an integer value, Python would at least throw an error (which is a good thing because in contrast to Method 1, you’d now be aware of the mistake)!

>>> list = 42
>>> isinstance(d[1], list)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    isinstance(d[1], list)
TypeError: isinstance() arg 2 must be a type or tuple of types

Yet, you should be made aware that using isinstance() is not a end-all be-all fix for this problem of overwriting the name list—it can still be done. However, it would work in fewer cases.