Tuples Checkpoint
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Show what you know about tuples: immutability, unpacking, swapping, starred names, and the tuples behind zip and enumerate.
Unpack, swap and split in one line
Unpacking replaces index reads. A swap needs no temporary name, and a starred name splits the first item from the rest.
order = ("Desk", 4, 150)name, qty, price = orderprint(name, qty * price)stock, sold = 20, 7stock, sold = sold, stockprint(stock, sold)first, *rest = (5, 6, 7)print(first, rest)Example 1 · Unpacking a function result
def totals(prices): return sum(prices), len(prices)
amount, count = totals([40, 60, 20])print(amount, count)print(amount / count)120 3 40.0
What this code does
- The function returns a tuple of two values.
- The caller unpacks it into
amountandcount. - Both names can then be used in a calculation.
The count of names must match the count of values, unless one starred name collects the extra items as a list.
Pair, number and sort
zip pairs two lists, enumerate numbers items, and tuples sort from the left. Together they replace most index loops.
names = ["Asha", "Ravi", "Meena"]marks = [82, 67, 91]ranked = sorted(zip(marks, names), reverse=True)for place, (mark, name) in enumerate(ranked, start=1): print(place, name, mark)Example 2 · Best and worst in one pass
marks = [72, 85, 64, 90]low, *_, high = sorted(marks)print(low, high)64 90
What this code does
sortedgives the marks from smallest to largest.lowtakes the first,hightakes the last.*_takes everything in the middle and ignores it.
Example 3 · Matching names with marks
names = ["Asha", "Ravi"]marks = [82, 67]pairs = list(zip(names, marks))print(pairs)print(pairs[0][0])[('Asha', 82), ('Ravi', 67)]
AshaWhat this code does
zipmakes one tuple per position.pairs[0]is the first tuple, andpairs[0][0]is its first item.
Each item of ranked is a (mark, name) tuple. The loop unpacks the place and the inner tuple in one line.
Finish up
Mark complete & continue
Next: String Indexing and Slicing