PythonMastery

Check the type of a variable in Python

Find out whether a value is an int, a float, a string or a list with type(), and test for a type with isinstance().

Every value in Python has a type. type() tells you what it is, and isinstance() checks whether a value is of a particular type.

The program

python
x = 3.14

print(type(x))
print(isinstance(x, float))
print(isinstance(x, int))
output
<class 'float'>
True
False

How it works

The common types

python
print(type(42))
print(type("hello"))
print(type([1, 2, 3]))
print(type(True))
output
<class 'int'>
<class 'str'>
<class 'list'>
<class 'bool'>

In real code, prefer isinstance() when you need to make a decision. It also accepts several types at once: isinstance(x, (int, float)) is True for any number.

Learn the idea: Variables & Data Types