Tuples
Part of the free LogicWiz Python course, Module 5: Lists and tuples. The examples and practice run in the app.
The GST slabs 5, 12, 18 and 28 should never change by accident in Canteen Counter. And Meher wants one function to give back both the total and the item count. Tuples do both.
You'll learn to
- Make tuples and know why they cannot be changed
- Spot the difference between `(5)` and `(5,)`
- Pack and unpack values, swap in one line, and return several values
Learn
A list that cannot change
A tuple is an ordered collection in round brackets: item = ("Samosa", 15).
- Indexing, slicing,
len,inand loops all work, just like a list. - But a tuple is immutable: no
append, noremove, not[0] = …. - It has only two methods:
countandindex.
Use a tuple for a fixed record (a name and a price, a row and a column, a date) and for values that must never change by accident.
Reading a tuple
item = ("Samosa", 15)
print(item[0], item[1])
print(len(item), item[-1])
slabs = (5, 12, 18, 28)
print(slabs[1:3])
print(slabs.count(12), slabs.index(18))
print(12 in slabs)
Try to change one
slabs = (5, 12, 18, 28)
slabs[0] = 0
TypeError: 'tuple' object does not support item assignment. That error is the whole point: the slabs are safe.
The comma makes the tuple
Brackets don't make a tuple; the comma does.
(5)is just the number 5 in brackets, like(2 + 3).(5,)is a tuple with one item.5, 6without brackets is already a tuple. This is called packing.()is the empty tuple.
The reverse is unpacking: name, price = ("Chai", 10) puts each item in its own name. The number of names must match the number of items.
(5) vs (5,)
a = (5)
b = (5,)
c = 5, 6
print(type(a), type(b), type(c))
print(c)
empty = ()
print(len(empty))
Unpack, swap, return two values
name, price = ("Chai", 10)
print(name, price)
x, y = 3, 7
x, y = y, x
print(x, y)
def low_high(marks):
return min(marks), max(marks)
lo, hi = low_high([67, 45, 89])
print(lo, hi)
return min(marks), max(marks) packs a tuple; lo, hi = … unpacks it. This is how a Python function "returns two values".
List or tuple?
| List [ ] | Tuple ( ) |
|---|---|
| mutable: append, remove, change items | immutable: fixed once made |
| many methods (sort, pop, insert…) | only count and index |
| a collection that grows: orders, a queue | a fixed record: (name, price), (row, col) |
| cannot be a dictionary key | can be a dictionary key (Module 6) |
Immutable means the tuple's slots can't be changed. If a slot holds a list, that list can still change: t = (1, [2, 3]) then t[1].append(4) works. And t += (4,) doesn't change t; it builds a new tuple and moves the label.
CBSE favourites: "What is the type of (5)?" (int), "find the error" in t[0] = 9 on a tuple, and "difference between a list and a tuple" (mutability, brackets, methods, use as keys). Interviews ask list vs tuple in almost every Python round.
In one line
Tuples are fixed lists: the comma makes one ((5,), not (5)); a, b = b, a swaps; return x, y returns a tuple you can unpack.