Python Data Types
Every value in Python has a type, and the built-in types cover text, numbers, sequences, mappings, sets, and more.
Types describe values
In Python the type belongs to the value, not to the variable. When you assign a value, Python records what kind of thing it is, and you can inspect that at any time with the built-in type() function. Knowing a value's type tells you which operations are allowed on it, for example that you can add numbers but concatenate strings.
Checking types with type()
x = 42
y = 3.14
name = "Python"
print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'>
print(type(name)) # <class 'str'>The built-in data types
Python groups its standard types by the kind of data they represent. The table below lists the most common ones you will meet early on, with a short example of each.
A useful way to group these is by whether they can be changed after creation. Mutable types can be modified in place, while immutable types cannot, so an operation that looks like a change actually produces a new value.
- Immutable types: int, float, complex, bool, str, tuple, and frozenset.
- Mutable types: list, dict, and set.
- Sequences (str, list, tuple, range) support indexing and slicing.
- The bool type is a special kind of int, where True equals 1 and False equals 0.
Values of several types
flag = True # bool
prices = [9.99, 19.99] # list of floats
person = {"name": "Lee"} # dict
nothing = None # NoneType
print(type(flag), type(prices), type(person), type(nothing))Exercise: Python Data Types
Which function tells you the data type of a variable?