Python Data Types
Python comes with a small set of built-in types covering numbers, text, collections, and a "no value" sentinel.
The built-ins
| Type | Example | Use for |
|---|---|---|
int | 42 | Whole numbers; unlimited size. |
float | 3.14 | Decimal numbers (binary IEEE-754). |
complex | 2 + 3j | Complex numbers — science, signal processing. |
bool | True / False | Logic. Subclass of int (True == 1). |
str | 'hello' | Unicode text. |
bytes | b'\\xff' | Raw binary data. |
list | [1, 2, 3] | Ordered, mutable. |
tuple | (1, 2) | Ordered, immutable. |
set | {1, 2, 3} | Unordered, unique. |
dict | {'a': 1} | Key→value mapping. Insertion-ordered. |
NoneType | None | "No value" sentinel. |
Mutable vs immutable
| Mutable (can change in place) | Immutable |
|---|---|
list, dict, set, custom classes | int, float, str, tuple, bool, None, frozenset |
Checking type
PYTHON
x = 42 print(type(x)) # <class 'int'> print(isinstance(x, int)) # True print(isinstance(x, (int, float))) # True
Tip: Prefer
isinstance(x, T) over type(x) is T. It respects subclasses, so it doesn't break when someone passes a subtype.Example
Example
examples = {
'int': 1,
'float': 3.14,
'str': 'hello',
'bool': True,
'list': [1, 2, 3],
'tuple': (1, 2),
'dict': {'a': 1},
'set': {1, 2, 3},
'none': None,
}
for k, v in examples.items():
print(k, type(v).__name__, v)
Try it Yourself »
Exercise
Which built-in returns the type of an object?
(x)
Four letters; same as the keyword in "type hints".
Discussion
Loading…