11.16 Hands-on Exercises
Practice programs reinforcing Python tuple concepts -- combining concatenation and membership, the packing/unpacking swap idiom, a multi-value data-processing function, and mini projects for server config, AWS region mapping, and an immutable config store.
Tuple Operations
Practice combining concatenation, membership, and slicing on a single tuple.
>>> t = (10, 20, 30)
>>> t = t + (40,) # "append" by concatenating a new tuple
>>> t
(10, 20, 30, 40)
>>> 20 in t
True
Packing & Unpacking
A swap function is the classic demonstration of packing and unpacking working together.
def swap(a, b):
return b, a
>>> swap(1, 2)
(2, 1)
Data Processing
Returning multiple related results from one function call, using a tuple as the return type.
def minmax(t):
return min(t), max(t)
>>> minmax((5, 2, 8, 1))
(1, 8)
Mini Projects
Server configuration — a fixed server record, unpacked wherever it’s used; the tuple guarantees the config can’t be accidentally mutated mid-script:
SERVER = ("web01", "10.0.1.5", 8080, "running")
def describe(server):
name, ip, port, status = server
return f"{name} ({ip}:{port}) is {status}"
>>> describe(SERVER)
'web01 (10.0.1.5:8080) is running'
AWS region mapper — mapping a fixed tuple of regions to their index, useful for consistent ordering or round-robin selection logic:
def region_mapper(regions):
return {r: i for i, r in enumerate(regions)}
>>> region_mapper(("us-east-1", "us-west-2", "eu-west-1"))
{'us-east-1': 0, 'us-west-2': 1, 'eu-west-1': 2}
Immutable configuration store — a tiny config object built entirely on tuples internally, guaranteeing nothing can silently rewrite a setting after construction:
class ImmutableConfig:
def __init__(self, **kwargs):
self._data = tuple(kwargs.items())
def get(self, key):
for k, v in self._data:
if k == key:
return v
return None
>>> config = ImmutableConfig(host="localhost", port=8080)
>>> config.get("host"), config.get("port")
('localhost', 8080)
Quick Interview Answer
“These exercises combine the chapter’s core ideas into small, realistic code: tuple concatenation as the ‘append’ equivalent, the packing/unpacking swap idiom, and multi-value returns via an implicit tuple. The mini projects apply the same pattern to real infrastructure use cases — a server record unpacked into named fields for a description string, mapping a fixed region tuple to indices for round-robin logic, and an
ImmutableConfigclass that stores its settings as a tuple of(key, value)pairs internally specifically so nothing downstream can silently rewrite a setting after construction.”
Common Mistakes
- Using
t = t + (x,)repeatedly in a hot loop to “grow” a tuple — each concatenation allocates and copies the whole thing; if the collection genuinely needs to grow, use a list and convert to a tuple once at the end. - Forgetting the trailing comma when building a single-value tuple inside
region_mapper-style code, silently producing the wrong type (see 11.2 Creating Tuples). - Implementing
ImmutableConfig.get()with a linear scan over many settings when a dict would be both simpler and faster — a tuple of pairs communicates immutability, but doesn’t have to be the only internal representation if lookup performance matters.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form