Method 1: Using isinstance()
The standard and recommended way to check whether an object is a list in Python is to use the isinstance(obj, list) function. It accepts an input object as the first argument and a list as the second argument to verify that the object is a list. If it is a list, returns True; otherwise, returns False.
def is_list(obj):
return isinstance(obj, list)
print(is_list([]))
# Output: True
print(is_list([1, 2, 3]))
# Output: True
print(is_list(tuple()))
# Output: False
print(is_list("hello"))
# Output: False
If an input is an empty list or a list with elements, it returns True.
Custom subclasses of list
The main advantage of the isinstance(obj, list) method is that it handles inheritance and returns True for custom subclasses of list. The key reason to use this approach.
class MyList(list):
def say_hi(self):
print("Hello, I'm a fancy list!")
class QuerySet(list):
def filter(self, *args): ...
class SortedList(list):
def append(self, item):
super().append(item)
self.sort()
print(isinstance(MyList(), list))
# Output: True
print(isinstance(QuerySet(), list))
# Output: True
print(isinstance(SortedList([3, 1, 2]), list))
# Output: True
In this code, we created three types of subclasses of the list. Since all are lists, the isinstance() method returns True, and it supports all the basic list functions like extend(), append(), or remove().
Method 2: Using type(obj) is list: Strict Type Match
If you want to enforce strict typing on an input variable, you can use the type() method.
list_obj = [1, 2, 3]
if type(list_obj) is list:
print("Exact list only, no subclasses")
# Output: Exact list only, no subclasses
Subclass of a list
The type() method does not accept subclasses and only accepts real lists. With the help of an if condition and is operator, it returns False for a subclass of a list.
class MyList(list):
def say_hi(self):
print("Hello, I'm a fancy list!")
class QuerySet(list):
def filter(self, *args): ...
class SortedList(list):
def append(self, item):
super().append(item)
self.sort()
print(type(MyList()) is list)
# Output: False
print(type(QuerySet()) is list)
# Output: False
print(type(SortedList()) is list)
# Output: False
In this code, we defined three classes that are subclasses of list, and for each subclass, type() returns False when passed a list.
It prevents accidental acceptance of custom list-like types, which can be an advantage in some cases.
That’s all!

