Loading lessons...
Data Types
Everything in Python is an object with a type. Setting a variable defines its type automatically.
Built-in types
| Category | Types |
|---|---|
| Text | str |
| Numbers | int, float, complex |
| Sequence | list, tuple, range |
| Mapping | dict |
| Set | set, frozenset |
| Boolean | bool |
| Binary | bytes, bytearray, memoryview |
| None | NoneType |
How to set a type
Just assign a value of that kind:
python
x = "Hello"
### str
x = 20
### int
x = 20.5
### float
x = 1j
### complex
x = ["a", "b"]
### list
x = ("a", "b")
### tuple
x = range(6)
### range
x = {"name": "Ada"}
### dict
x = {"a", "b"}
### set
x = True
### bool
x = None
### NoneType
Specify a type with constructors
You can also force a type using the type name:
python
x = str("Hello")
x = int(20)
x = list(("a", "b"))
x = dict(name="Ada", age=36)
Check a type
Use type() to ask Python what a value is.
python
print(type(20))
### <class 'int'>
print(type([1, 2]))
### <class 'list'>
Mutable vs immutable
- Mutable types can change after creation:
list,set,dict. - Immutable types cannot change:
str,tuple,int,bool,frozenset.
TL;DR
- The value decides the type;
type()reveals it. - Core types: str, int, float, list, tuple, dict, set, bool.
- Use constructors like
str(),list()to force a type. - Lists, sets, dicts are mutable; strings and tuples are immutable.