Tuples in Python
Create tuples, use them like read-only lists, pack and unpack values, and know when a tuple is a better choice than a list.
Learning objectives
- βCreate tuples, including empty and single-item tuples
- βIndex, slice and loop over tuples, and use count() and index()
- βPack and unpack values with tuple assignment
- βDecide when to use a tuple instead of a list
π‘ Key points
- A tuple is an ordered, immutable sequence, usually written with round brackets: (10, 20, 30).
- The comma makes the tuple, not the brackets: (5) is just the int 5, but (5,) is a one-item tuple.
- Indexing, slicing, +, *, in and for loops work just like lists; assigning to or deleting an item raises TypeError.
- Tuples have only two methods: count(x) and index(x). len(), min(), max(), sum() and sorted() also work (sorted() returns a list).
- Tuple assignment unpacks values in one line: name, marks = ('Amit', 87).
- Tuples can be dictionary keys and set items; lists cannot, because lists can change.
- A tuple that holds a list cannot be reassigned, but the list inside it can still be modified.
π» Code examples(6)
marks = (87, 92, 76)
point = 3, 4 # brackets are optional
empty = ()
one = (5,) # trailing comma needed
not_tuple = (5) # just an int!
print(type(marks), type(point))
print(type(one), type(not_tuple))
print(len(empty))
print(tuple("abc"))
print(tuple([1, 2, 3]))
<class 'tuple'> <class 'tuple'>
<class 'tuple'> <class 'int'>
0
('a', 'b', 'c')
(1, 2, 3)days = ("Mon", "Tue", "Wed", "Thu", "Fri")
print(days[0], days[-1])
print(days[1:3])
print(days + ("Sat",)) # join β new tuple
print(("Hi",) * 3) # repeat
print("Wed" in days)
print(len(days))
Mon Fri
('Tue', 'Wed')
('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')
('Hi', 'Hi', 'Hi')
True
5t = (10, 20, 30)
# t[0] = 99 # TypeError: 'tuple' object does
# # not support item assignment
t = (99,) + t[1:] # make a new tuple instead
print(t)
data = ("Amit", [87, 92])
data[1].append(76) # the list inside can change
print(data)
(99, 20, 30)
('Amit', [87, 92, 76])scores = (45, 78, 45, 90, 62, 45)
print(scores.count(45)) # how many 45s
print(scores.index(90)) # position of 90
print(len(scores), min(scores), max(scores))
print(sum(scores))
print(sorted(scores)) # gives a list
print(tuple(sorted(scores)))
3 3 6 45 90 365 [45, 45, 45, 62, 78, 90] (45, 45, 45, 62, 78, 90)
student = ("Priya", 12, "A") # packing
name, cls, section = student # unpacking
print(name, cls, section)
first, *rest = (90, 85, 77, 64)
print(first, rest)
def min_max(nums):
return min(nums), max(nums) # a tuple
lo, hi = min_max((34, 12, 78, 56))
print(lo, hi)
Priya 12 A 90 [85, 77, 64] 12 78
results = (("Amit", 87), ("Priya", 92),
("Ravi", 76))
for name, marks in results:
print(f"{name:<6} {marks}")
best = max(results, key=lambda r: r[1])
print("Topper:", best[0])
Amit 87 Priya 92 Ravi 76 Topper: Priya
π― Practice
Q1. Which of these is a tuple: (7) or (7,)?+
(7,). Without the comma, (7) is just the integer 7 in brackets.
Q2. What is the output of t = (1, 2, 3) * 2; print(len(t))?+
6 β t becomes (1, 2, 3, 1, 2, 3).
Q3. grades = ('A', 'B', 'A', 'C', 'A'). Print how many times 'A' appears and where 'C' is.+
print(grades.count('A')) # 3 print(grades.index('C')) # 3
Q4. Can you sort a tuple t with t.sort()?+
No. Tuples have no sort() method because they cannot change. Use sorted(t), which returns a list, or tuple(sorted(t)) for a tuple.
Q5. t = (10, 20, 30, 40). Unpack the first value into a and the rest into b.+
a, *b = t # a = 10, b = [20, 30, 40]
π Notes
Tuple or list?
Use a list when the collection will grow, shrink or change: a shopping cart, a queue of tasks, marks you are still entering.
Use a tuple when the values belong together and should stay fixed:
- coordinates
(x, y) - a date
(15, 8, 1947) - the days of the week
- a record you only read, like
("Amit", 12, "A")
Tuples also protect data from accidental changes. If a function receives a tuple, you know it cannot add, remove or replace its items.
Tuples as dictionary keys
Because tuples are immutable, they can be used as keys in a dictionary (tomorrow's topic). Lists cannot:
seats = {(1, "A"): "Amit", (1, "B"): "Priya"}
print(seats[(1, "B")]) # Priya
Trying {[1, "A"]: "Amit"} raises TypeError: unhashable type: 'list'.
Nested tuples
A tuple can contain other tuples. Use two indexes to reach inside:
table = ((1, 2, 3), (4, 5, 6))
print(table[1][2]) # 6
Common mistakes
- Missing comma:
("Maths")is a string, not a tuple. Write("Maths",). - Calling list methods:
t.append(5)raises AttributeError. Convert first:lst = list(t), change it, thent = tuple(lst). - Unpacking the wrong count:
a, b = (1, 2, 3)raises ValueError: too many values to unpack. Match the number of names, or use*rest. - Expecting sorted() to give a tuple: it always returns a list.
Next: Day 13 β Dictionaries, for looking up values by a key instead of a position.