In Python we can get the data types of an object with the type
command (type(object)
). For example:
x = 5 type(x)
int
x = [1,2,3] type(x)
list
However, this approach does not work in the if statements as we can see below:
x = [1,2,3] if type(x)=='list': print("This is a list") else: print("I didn't find any list")
I didn't find any list
For that reason, we should work with the isinstance(object, type)
function. For example:
x = [1,2,3] if isinstance(x, list): print("This is a list") elif isinstance(x, int): print("This is an integer") else: print("This is neither list nor integer")
This is a list
x = 5 if isinstance(x, list): print("This is a list") elif isinstance(x, int): print("This is an integer") else: print("This is neither list nor integer")
This is an integer
x = "5" if isinstance(x, list): print("This is a list") elif isinstance(x, int): print("This is an integer") else: print("This is neither list nor integer")
This is neither list nor integer