There are various way that we can use to tell whether an object is a list
or not.
Using the isinstance() function
The builtin isinstnace() function is used to tell whether an object is an instance of the specified class. The function takes two arguments, the object and the target class.
isinstance(obj, cls)
The function returns a boolean value(True
or False
) indicating whether obj
is an instance of cls
or not. We can use the function with the class list
as the target parameter to tell whether the object is a list or not.
object1 = 'Python'
object2 = (1, 2, 3)
object3 = [1, 2, 3, 4]
def is_list(obj):
return isinstance(obj, list)
print(is_list(object1))
print(is_list(object2))
print(is_list(object3))
Using the type() Function
The builtin type()
function is used to check the type/class of the object given as an argument.
type(obj)
We can specify the object to be checked as the argument and then use a conditional statement to check whether the returned type is the builtin list
class.
object1 = {'Python', 'Java', 'PHP'}
object2 = ('Python', 'Java','PHP')
object3 = ['Python', 'Java', 'PHP']
def is_list(obj):
#use the type() function
obj_type = type(obj)
#use an if statement to check whether the returned value is the list class
if obj_type == list:
return True
return False
print(is_list(object1))
print(is_list(object2))
print(is_list(object3))
Using the __class__ attribute
Each object in Python contains an attribute __class__
that references the class/type the object belongs to. In the case with lists the __class__
attribute will reference the list
class. We can use this attribute to tell if an object is a list or not depending on whether the __class__
attribute is set to list
.
object1 = ['Python', 'Java', 'PHP']
object2 = (1, 2, 3)
object3 = {'one': 1, 'two': 2}
def is_list(obj):
if obj.__class__ == list:
return True
return False
print(is_list(object1))
print(is_list(object2))
print(is_list(object3))