- Python: Check if Variable is a List
- Check if Variable is a List with type()
- Check if Variable is a List with is Operator
- Check if Variable is a List with isinstance()
- Free eBook: Git Essentials
- Conclusion
- Check Given Object is a List or not in Python
- 1. Quick Examples to Check Whether Object is List or Not
- 2. Using isinstance() to Check If Object is List in Python
- 3. Using isinstance() with typing.List
- 4. Check If Given Object is List Using type()
- 5. Using __class__
- 6. Conclusion
- You may also like reading:
- How to Check if an Object is of Type List in Python?
- Method 1: type(object) == list
- Method 2: isinstance(object, list)
Python: Check if Variable is a List
Python is a dynamically typed language, and the variable data types are inferred without explicit intervention by the developer.
If we had code that needed a list but lacked type hints, which are optional, how can we avoid errors if the variable used is not a list?
In this tutorial, we’ll take a look at how to check if a variable is a list in Python, using the type() and isinstance() functions, as well as the is operator:
Developers usually use type() and is , though these can be limited in certain contexts, in which case, it’s better to use the isinstance() function.
Check if Variable is a List with type()
The built-in type() function can be used to return the data type of an object. Let’s create a Dictionary, Tuple and List and use the type() function to check if a variable is a list or not:
grocery_list = ["milk", "cereal", "ice-cream"] aDict = "username": "Daniel", "age": 27, "gender": "Male"> aTuple = ("apple", "banana", "cashew") # Prints the type of each variable print("The type of grocery_list is ", type(grocery_list)) print("The type of aDict is ", type(aDict)) print("The type of aTuple is ", type(aTuple))
The type of grocery_list is class 'list'> The type of aDict is class 'dict'> The type of aTuple is class 'tuple'>
Now, to alter code flow programmatically, based on the results of this function:
a_list = [1, 2, 3, 4, 5] # Checks if the variable "a_list" is a list if type(a_list) == list: print("Variable is a list.") else: print("Variable is not a list.")
Check if Variable is a List with is Operator
The is operator is used to compare identities in Python. That is to say, it’s used to check if two objects refer to the same location in memory.
The result of type(variable) will always point to the same memory location as the class of that variable . So, if we compare the results of the type() function on our variable with the list class, it’ll return True if our variable is a list.
Let’s take a look at the is operator:
a_list = [1, 2, 3, 4, 5] print(type(a_list) is list)
Since this might look off to some, let’s do a sanity check for this approach, and compare the IDs of the objects in memory as well:
print("Memory address of 'list' class:", id(list)) print("Memory address of 'type(a_list)':", id(type(a_list)))
Now, these should return the same number:
Memory address of 'list' class: 4363151680 Memory address of 'type(a_list)': 4363151680
Note: You’ll need to keep any subtypes in mind if you’ve opted for this approach. If you compare the type() result of any list sub-type, with the list class, it’ll return False , even though the variable is-a list, although, a subclass of it.
This shortfall of the is operator is fixed in the next approach — using the isinstance() function.
Check if Variable is a List with isinstance()
The isinstance() function is another built-in function that allows you to check the data type of a variable. The function takes two arguments — the variable we’re checking the type for, and the type we’re looking for.
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
This function also takes sub-classes into consideration, so any list sub-classes will also return True for being an instance of the list .
Let’s try this out with a regular list and a UserList from the collections framework:
from collections import UserList regular_list = [1, 2, 3, 4, 5] user_list = [6, 7, 8, 9, 10] # Checks if the variable "a_list" is a list if isinstance(regular_list, list): print("'regular_list' is a list.") else: print("'regular_list' is not a list.") # Checks if the variable "a_string" is a list if isinstance(user_list, list): print("'user_list' is a list.") else: print("'user_list' is not a list.")
Running this code results in:
'regular_list' is a list. 'user_list' is a list.
Conclusion
Python is a dynamically typed language, and sometimes, due to user-error, we might deal with an unexpected data type.
In this tutorial, we’ve gone over three ways to check if a variable is a list in Python — the type() function, the is operator and isinstance() function.
Check Given Object is a List or not in Python
How to check if a given object is a list or not in Python? In python, there are several ways to check if the given object is a list or not. When you use these methods, you need to specify what type you are checking with and if the object is that specific type it returns True or else Flase. In our case, we need to specify the list as an argument.
The following are methods to check if an object is a list or not
- Using isinstance()
- Using isinstance() with typing.List
- Using type()
- Using __class__
1. Quick Examples to Check Whether Object is List or Not
Following are quick examples to check if the object is a List or not in python.
# Below are some quick examples. # Using isinstance() if (isinstance(countries, list)): print("List") else: print("not a List") # Using isinstance() with typing.List if (isinstance(countries, typing.List)): print("List") else: print("not a List") # Using type() if (type(countries) is list): print("List") else: print("not a List") # Using __class__ if (countries.__class__ == list): print("List") else: print("not a List")
2. Using isinstance() to Check If Object is List in Python
The isinstance() method in python is used to check if the given object is a list or not. Actually, this method is used to check if object of a specific type, not just lists. This method takes two parameters first, the object, and second the type you wanted to check with. If the input object is of a specified type, it returns True, otherwise False is returned.
Here, we will pass our object as the first parameter and list as the second parameter. Let’s see how to use isinstance() method.
# Syntax isinstance(object, list)
Let’s create two objects, one is a string and another is a list of countries. We will check if both are list objects or not using isinstance() method.
countries=['Russia', 'Japan', 'Mexico', 'Europe'] city='Guntur' # Using isinstance() to check countries is list if (isinstance(countries, list)): print("List") else: print("not a List") # Using isinstance() to check city is list if (isinstance(city, list)): print("List") else: print("not a List")
We can see that countries is a List type and city is not a list.
3. Using isinstance() with typing.List
It is similar to the above method. But, we will pass typing List as a second parameter to the isinstance() method instead of list. Here, typing is a module that we need to import.
Let’s see how to use isinstance() method with typing.List.
# Syntax isinstance(object, typing.List)
Let’s use two objects. One is a string and another is a list of countries. We will check if both are list objects or not using isinstance () method.
import typing # Using isinstance() with typing.list to check countries is list if (isinstance(countries, typing.List)): print("List") else: print("not a List") # Using isinstance() with typing.list to check city is list if (isinstance(city, typing.List)): print("List") else: print("not a List")
Yields the same output as above.
4. Check If Given Object is List Using type()
type() will return the type of the object. Here, we will compare the object returning type with the list using is operator. If the object is a list, True is returned, Otherwise False is returned. Let’s see the syntax of type() with is operator.
# Syntax type(object) is list
Let’s use it with an example.
# Using type() to check countries is list if (type(countries) is list): print("List") else: print("not a List") # Using type() to check city is list if (type(city) is list): print("List") else: print("not a List") # Output: # List # not a List
5. Using __class__
In Python __class__ will return the class of the given object. Here, we will compare the object with list using == operator. If the object is list, True is returned, Otherwise False is returned. Let’s see an example
# Using __class__ to check countries is list if (countries.__class__ == list): print("List") else: print("not a List") # Using _class_ to check city is list if (city.__class__ == list): print("List") else: print("not a List") # Output: # List # not a List
6. Conclusion
We have seen several ways to check if the object is a list or not in python using isinstance() , and isinstance() with typing.List , type() and __class__ . In all these methods, we used a if statement that will print a statement specifying whether the object is a list or not.
With most of these methods, you need to specify what type you are checking with and if the object is that specific type it returns True or else Flase. In our case, we need to specify the list as an argument.
You may also like reading:
How to Check if an Object is of Type List in Python?
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 dictCheck if object is list python 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 .
If you check for a non-list, the return value is 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 = >>> 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:
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 = >>> 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 "", line 1, in 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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Be on the Right Side of Change 🚀
- The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
- Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
- Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.
Learning Resources 🧑💻
⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!
Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.
New Finxter Tutorials:
Finxter Categories: