built-in types, mutability, strings, collections, type hints
3.0 Prologue
This chapter examines how Python represents data. Understanding the built-in types,
their mutability rules, and how to annotate types with hints makes programs clearer
and more robust.
Strings (str) are immutable sequences of Unicode code points. String literals
accept single, double, or triple quotes. Common forms:
name = "Alice"
path = r"C:\Users\Alice" # raw string — backslashes are literal
msg = f"Hello, {name}!" # f-string interpolation (3.6+)
blob = b"bytes literal" # bytes, not str
doc = """
multi-line
string
"""
Key string methods: split(), join(), strip(),
replace(), startswith(), find(), format().
Strings support slicing: s[1:4], s[::-1] (reverse).
3.3 Lists and Tuples
Lists are mutable, ordered sequences. They support index, slice,
append, insert, remove, and sort operations:
nums = [3, 1, 4, 1, 5, 9]
nums.append(2)
nums.sort()
print(nums[0], nums[-1]) # 1 9
sub = nums[2:5] # slice — new list
Tuples are immutable ordered sequences, often used for
heterogeneous records. Parentheses are optional:
point = 3.0, 4.0 — tuple unpacking: x, y = point.
3.4 Dictionaries
dict maps hashable keys to arbitrary values. Insertion order is preserved
(Python 3.7+):
scores = {"Alice": 95, "Bob": 87}
scores["Carol"] = 91
print(scores.get("Dave", 0)) # 0 — default when key absent
for name, score in scores.items():
print(f"{name}: {score}")
The merge operator | (3.9+) combines dicts:
merged = d1 | d2. Use setdefault() or
collections.defaultdict to avoid KeyError on missing keys.
3.5 Sets
set is an unordered collection of unique hashable objects.
frozenset is the immutable variant (hashable itself, usable as dict key).
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union: {1, 2, 3, 4, 5, 6}
print(a & b) # intersection: {3, 4}
print(a - b) # difference: {1, 2}
print(a ^ b) # symmetric: {1, 2, 5, 6}
3.6 Type Hints
Type hints (PEP 484, Python 3.5+) annotate variables, parameters, and return values.
They are not enforced at runtime but enable static analysis with mypy,
pyright, and IDE autocompletion.
from typing import Optional
def find_user(uid: int) -> Optional[str]:
users = {1: "Alice", 2: "Bob"}
return users.get(uid) # returns str or None
# Python 3.10+ — use X | Y instead of Optional[X]
def find_user(uid: int) -> str | None:
...
Common hint types: list[int], dict[str, float],
tuple[int, str], set[str], Callable[[int], bool],
Any.
3.7 Type Conversion
Python does not perform implicit numeric widening (except in arithmetic expressions).
Use explicit constructors to convert between types:
int("42") # 42
float(7) # 7.0
str(3.14) # '3.14'
bool(0) # False (0, 0.0, "", [], {}, None are falsy)
list((1, 2, 3)) # [1, 2, 3]
tuple([1, 2, 3]) # (1, 2, 3)
set([1, 2, 2, 3]) # {1, 2, 3}
3.8 Epilogue
This chapter covered Python's core data types: scalars, strings, sequences, mappings,
sets, type hints, and conversion. The next chapter focuses on operations — how data
is transformed through functions, decorators, and comprehensions.