A data type defines what kind of value something is and which operations can be done with it. Python is dynamically typed (the type is attached to the value, not to the variable) and strongly typed (it does not silently mix incompatible types: "2" + 3 raises an error).
Built-in data types
| Category | Type | Example |
|---|---|---|
| Numbers | int | 42 |
| Numbers | float | 3.14 |
| Numbers | complex | 2 + 3j |
| Logic | bool | True, False |
| Text | str | "Hello" |
| Sequences | list | [1, 2, 3] |
| Sequences | tuple | (1, 2, 3) |
| Mappings | dict | {"name": "Ana", "age": 25} |
| Sets | set | {1, 2, 3} |
| Nothing | NoneType | None |
Checking the type of a value
print(type(42)) # <class 'int'>
print(type("Hello")) # <class 'str'>
print(isinstance(3.14, float)) # True
Mutable and immutable types
- Immutable values cannot be modified after they are created:
int,float,bool,str,tuple. Any change creates a new value. - Mutable values can be changed in place:
list,dict,set.
numbers = [1, 2, 3]
numbers.append(4) # the same list now has 4 elements
text = "hello"
# text[0] = "H" # error: strings are immutable
text = "H" + text[1:] # creates a new string
Everything is an object
In Python even numbers and text are objects, with their own methods:
print("python".upper()) # PYTHON
print((255).bit_length()) # 8
In the next articles you will see the basic data types in detail and how to convert one type into another.