Python Data Types

Tutorial 5 of 65 · pythondeck.com Python course

Core built-in types include numeric (int, float, complex, bool), text (str), binary (bytes, bytearray, memoryview), sequences (list, tuple, range), mappings (dict), sets (set, frozenset) and the singletons None, True, False. Types can be checked with type() or isinstance().

Data types describe what operations are valid on a value. Python's built-in types—numeric, sequence, mapping, set, boolean, binary, None—form the vocabulary of everyday programs.

Type checks at runtime (isinstance) and optional static hints help you handle user input, API payloads, and edge cases without silent coercion bugs.

type(obj) returns the class; prefer isinstance(obj, cls) for subclasses.

Scalars: int, float, complex, bool, NoneType.

Sequences: str, list, tuple, range, bytes types.

Mappings: dict; sets: set, frozenset.

Truthiness: empty containers and zero numerics are falsy; most objects are truthy.

Dynamic typing plus duck typing: use behavior (methods) not nominal type alone.

Everything inherits from object. User classes can implement protocols (__iter__, __len__) so they work with built-in functions without sharing a base class beyond object.

Coercion is explicit in modern Python: int("3") works; "3" + 4 raises TypeError. Design functions to accept the narrowest type you need, or document conversions clearly.

collections.abc defines interfaces; JSON decodes to dict/list/scalars—validate shapes before logic runs.

Using type(x) == list instead of isinstance(x, list) and breaking subclasses.

Comparing incompatible types with < in Python 3 (TypeError).

Storing mixed types in one list without a documented schema, then failing silently later.

Confusing is (identity) with == (equality), especially for small ints and strings interning.

Validate external input early and convert to the types your logic expects.

Use dataclasses or typed dicts for structured records in larger apps.

Document expected types in docstrings; add hints where the team uses mypy or pyright.

Prefer explicit constructors (datetime.fromisoformat) over fragile string parsing.

Log types you receive at API boundaries once during integration, then enforce conversions centrally.

Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.

The program below demonstrates type inspection. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Example: Type inspection
# Run in the REPL or save as a .py file and execute with python.
values = [42, 3.14, True, "hi", [1,2], (1,2), {1,2}, {"k":1}, None]
for v in values:
    print(type(v).__name__, "->", v)

This sample walks through isinstance in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Example: isinstance
# Run in the REPL or save as a .py file and execute with python.
x = 7
print(isinstance(x, int))   # True
print(isinstance(x, (int, float)))  # True

Here is a hands-on illustration of conversion. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.

# Example: Conversion
# Run in the REPL or save as a .py file and execute with python.
n = int("42")
f = float("3.14")
s = str(2025)
print(n, f, s, type(n))

The program below demonstrates isinstance checks. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Prefer isinstance over type() for inheritance-aware checks
values = [42, 3.14, True, "hi", [1], (1,), {1}, {1: 2}, None]
for v in values:  # inspect each sample object
    print(type(v).__name__, isinstance(v, (int, float)))  # numeric?
print(isinstance(True, int))  # bool subclasses int in Python
print(isinstance(3.14, int))  # False for true float
label = "score"  # string key name
mapping = {label: 99}  # dict uses hashable key
print(mapping[label])  # 99
frozen = frozenset([1, 2, 2])  # duplicates collapse
print(frozen, len(frozen))  # frozenset({1, 2}) 2

This sample walks through safe conversions in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Conversions can raise ValueError; validate before converting user text
raw = "42"  # digits only — safe for int()
number = int(raw)  # string -> int
print(number + 8)  # 50
ratio = float("3.14")  # string -> float
print(ratio * 2)  # 6.28
flag = bool("")  # empty string is falsy
print(flag)  # False
flag2 = bool("yes")  # non-empty string is truthy
print(flag2)  # True
bits = bytes([65, 66, 67])  # immutable byte sequence
print(bits.decode("ascii"))  # ABC

« Python Variables All tutorials Python Numbers »