Python | Check If A Given Object Is A List Or Not (original) (raw)
Last Updated : 16 Apr, 2025
Given an object, the task is to check whether the object is a list or not. Python provides few simple methods to do this and in this article, we'll walk through the different ways to check if an object is a list:
Using isinstance()
**isinstance() function checks if an object is an instance of a specific class or data type.
Python `
if isinstance([1, 2, 3], list): print("Object is a list") else: print("Object is not a list")
if isinstance("12345", list): print("Object is a list") else: print("Object is not a list")
`
Output
Object is a list Object is not a list
**Explanation: isinstance(obj, list) returns **True if obj is a and False if it's not.
Using type()
Another method to check if an object is a list is by using the type() function. This function returns the exact type of an object.
Python `
l1 = [1, 2, 3] l2 = (10, 20, 30) # A tuple
if type(l1) is list: print("Object is a list") else: print("Object is not a list")
if type(l2) is list: print("Object is a list") else: print("Object is not a list")
`
Output
Object is a list Object is not a list
**Explanation:
- **type(obj) returns the exact type (e.g., list, tuple, dict).
- Unlike **isinstance(), it does not consider inheritance, useful when strict type matching is needed.
Using __class__ Attribute
To check if an object is a list , we can use the __class__ attribute and compare it to the list type:
Python `
l1 = [1, 2, 3, 4, 5] l2 = (12, 22, 33)
if l1.class == list: print("input is a list") else: print("input is not a list")
if l2.class == list: print("input is a list") else: print("input is not a list")
`
Output
input is a list input is not a list
**Explanation:
- **__class__ returns the class of an object.
- While it works, it’s less readable and not as commonly used as **isinstance().