Python Data Types
Python · Variables & Data Types
Theory
Every value in Python has a type that decides what you can do with it. The core built-in types are: numbers (int, float, complex), text (str), booleans (bool), sequences (list, tuple, range), sets (set, frozenset), mappings (dict) and the special value None of type NoneType. type(value) tells you which one you have, and isinstance(value, int) checks it in a way that also accepts subclasses.
The most important split is mutable versus immutable. Immutable types (int, float, str, bool, tuple, frozenset) can never change after creation; any 'change' creates a new object. Mutable types (list, dict, set) can be modified in place, so every name pointing at them sees the change. Only immutable, hashable values can be dictionary keys or set members, which is why a list cannot be a dict key but a tuple can.
Why we use it
The type decides which operations are legal: 5 + 5 is 10, '5' + '5' is '55', and '5' + 5 is a TypeError. Knowing types lets you predict results, read error messages and pick the right container for your data.
When to use it
Use type() or isinstance() when debugging unexpected results or validating input. Pick list for ordered changeable data, tuple for fixed records, set for unique items, and dict for lookups by key. Prefer isinstance() over type() == in real code.
How it works
- You have a value, e.g. 3.14
- Python stores it as an object that carries its type
- Call type(3.14) to inspect it
- Is the type mutable (list, dict, set)? Yes: Can change in place; all names see it. No: Changes make a new object.
- Choose operations that type supports
- Output: <class 'float'>
Syntax
type(variable)Example
type(3.14) # floatKey points
- Use type() to check a value's data type
- Numeric, sequence, mapping and boolean types cover most use cases
- Immutable: int, float, str, bool, tuple. Mutable: list, dict, set
- Only hashable (immutable) values can be dict keys or set items
- isinstance(x, (int, float)) checks against several types at once