Python | Check if a given object is list or not
Last Updated :
02 Jan, 2023
Given an object, the task is to check whether the object is list or not. Method #1: Using isinstance
Python3
ini_list1 = [ 1 , 2 , 3 , 4 , 5 ]
ini_list2 = '12345'
if isinstance (ini_list1, list ):
print ("your object is a list !")
else :
print ("your object is not a list ")
if isinstance (ini_list2, list ):
print ("your object is a list ")
else :
print ("your object is not a list ")
|
Output:
your object is a list !
your object is not a list
Method #2: Using type(x)
Python3
ini_list1 = [ 1 , 2 , 3 , 4 , 5 ]
ini_list2 = ( 12 , 22 , 33 )
if type (ini_list1) is list :
print ("your object is a list ")
else :
print ("your object is not a list ")
if type (ini_list2) is list :
print ("your object is a list ")
else :
print ("your object is not a list ")
|
Output:
your object is a list
your object is not a list
Method #3: Using __class__
To check if an object is a list , you can use the __class__ attribute and compare it to the list type:
Python3
ini_list1 = [ 1 , 2 , 3 , 4 , 5 ]
ini_list2 = ( 12 , 22 , 33 )
if ini_list1.__class__ = = list :
print ( "ini_list1 is a list" )
else :
print ( "ini_list1 is not a list" )
if ini_list2.__class__ = = list :
print ( "ini_list2 is a list" )
else :
print ( "ini_list2 is not a list" )
|
Output
ini_list1 is a list
ini_list2 is not a list
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...