PythonBuilt-in functions
type()
Returns the type of an object.
- Returns
- A type object, e.g.
<class 'int'>.
Example
#Python
print(type(42))
print(type("42"))
print(type([1, 2]))
print(type(3.5).__name__)Resultsaved result, you can check it
<class 'int'>
<class 'str'>
<class 'list'>
float
Definition and usage
#The type() function, called with a single argument, returns the type of the given value, for example int, str, list, or the name of your own class. It's a handy tool for checking what you're dealing with, especially while learning and while hunting for bugs.
You can read the type name as a string through the __name__ attribute: type(x).__name__.
To check a type inside a condition, isinstance() is the better choice, because it accounts for inheritance. type(x) == int returns False for the value True, even though bool is a subtype of int.
Syntax
#Syntax
type(object)Parameters
#object
any value
The value whose type you want to check.
Good practices
#- In conditions, use
isinstance(x, int)instead oftype(x) == int. - When a function behaves "strangely", print the
type()of its arguments. A number often turns out to be a string.
Related entries
#Spotted a mistake or missing an example? Write to us.