11.16 Hands-on Exercises
Tuple Operations Practice combining concatenation, membership, and slicing on a single tuple. >>> t = (10, 20, 30) >>> t = …
Tuple Operations Practice combining concatenation, membership, and slicing on a single tuple. >>> t = (10, 20, 30) >>> t = …
Conceptual Questions What’s the difference between a tuple and a list? Why does (1) not create a tuple, but (1,) does? Why are tuples …
When to Use Tuples The data represents a fixed record (coordinates, RGB values, a database row). The value needs to be a dict key or set …
Single-Element Tuple Forgetting the trailing comma — (1) is an int, not a tuple (see 11.2 Creating Tuples). This silently produces the wrong …
Tuples and File Handling Files store plain text, so “reading a tuple” means parsing each line and explicitly reconstructing the …
Search and aggregate operations on a tuple use the exact same techniques as on a list (see 10.12 Sorting and Searching and 10.14 Common …
flowchart TD A["Memory (3 items)"] --> A1["tuple: 64 bytes"] A --> A2["list: 88 bytes"] B["Literal creation speed"] --> B1["tuple: faster"] …
The general mutable-vs-immutable distinction is covered in 5.9 Mutable vs Immutable Types, and general copying mechanics in 6.5 Copying …
Creating and Accessing >>> nested = ((1, 2, 3), (4, 5, 6)) >>> nested[1][2] 6 Updating Nested Mutable Objects A …
Built-in Functions The same general-purpose sequence functions that work on lists (see 10.8 Built-in Functions) work identically on tuples. …
Tuples have only two methods — a direct consequence of immutability. Every method that would modify a list (append, remove, sort, …; …
+ (Concatenation) Combines two tuples into a new tuple — since tuples are immutable, this can never modify either original. >>> (1, …
flowchart LR P1["1"] --> PK["packing"] P2["2"] --> PK P3["3"] --> PK PK --> PT["point = (1, 2, 3)"] PT --> UP["unpacking"] UP --> U1["x = …
Identical indexing and slicing rules to lists (see 10.3 List Indexing and Slicing) and strings — only the container type, and one copying …
Empty Tuple >>> t = () >>> t () Single-Element Tuple A tuple with exactly one element requires a trailing comma — (1) is …
What Is a Tuple? What Is It? An ordered, immutable collection — like a list, but once created it can never be changed. Written with …