How to determine a Python variable's type?
In Python, you can determine the type of a variable by using the type()
function. For example:
x = 5
print(type(x)) # Output: <class 'int'>
y = 'hello'
print(type(y)) # Output: <class 'str'>
z = [1, 2, 3]
print(type(z)) # Output: <class 'list'>
Watch a video course
Python - The Practical Guide
You can also use the isinstance()
function to check if a variable is an instance of a particular type. For example:
x = 5
print(isinstance(x, int)) # Output: True
print(isinstance(x, str)) # Output: False
y = 'hello'
print(isinstance(y, str)) # Output: True
print(isinstance(y, int)) # Output: False
z = [1, 2, 3]
print(isinstance(z, list)) # Output: True
print(isinstance(z, tuple)) # Output: False