W3docs

How to determine a Python variable's type?

In Python, you can determine the type of a variable by using the type() function.

In Python, you can determine the type of a variable by using the type() function. For example:

Determining the type of a variable by using the type function in Python

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'>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use the isinstance() function to check if a variable is an instance of a particular type. For example:

Determining the type of a variable by using the isinstance function in Python

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