Programmer's Picnic · Python Foundations · 0 → ∞
Python Tuples: From 0 to Infinity
Make reliable fixed-size records and unpack them into readable code.
How to learn
Read one level, type the code into the editor, predict the output, then run it. Change one line and observe the result before proceeding. All code examples work with standard Python 3 (the dictionary union example requires 3.9 or newer).
The course moves from first principles to realistic code, common mistakes, performance and a mini-project.
0 · Meet the tuple
A tuple is an ordered sequence whose positions cannot be reassigned. It can contain duplicate items and different types.
person = ('Asha', 21, 'Varanasi')
print(person)
print(type(person).__name__)
print(person[0])('Asha', 21, 'Varanasi')
tuple
AshaRemember: The comma, not just the parentheses, creates a tuple in most expressions.
1 · Zero and one-element tuples
An empty tuple uses (). A one-element tuple needs a trailing comma. Parentheses alone group expressions.
empty = ()
one = ('Python',)
not_a_tuple = ('Python')
print(type(one).__name__)
print(type(not_a_tuple).__name__)
print(len(empty))tuple
str
0Remember: You can also write one = 'Python', but parentheses improve readability.
2 · Index, slice and membership
Tuples follow the same indexing and slicing rules as lists and strings. Slicing creates a new tuple.
colours = ('red', 'green', 'blue', 'green')
print(colours[-1])
print(colours[:2])
print(colours.count('green'))
print(colours.index('blue'))green
('red', 'green')
2
2Remember: Use in before index() if the target may be missing.
3 · Understand immutability
A tuple cannot be resized or assigned to by index. However, a mutable object inside a tuple can still change.
record = ('Asha', ['Python'])
record[1].append('SQL')
print(record)
# record[0] = 'Ravi' # TypeError('Asha', ['Python', 'SQL'])Remember: Immutable container does not mean recursively immutable content.
4 · Packing and unpacking
Put values together in a tuple (packing), then assign them to multiple names (unpacking). The number of destinations must match.
point = (4, 9)
x, y = point
print(x, y)
a, b = (1, 2)
a, b = b, a
print(a, b)4 9
2 1Remember: Use simple x, y = point; for swapping two values, write a, b = b, a.
5 · Starred unpacking
Use one starred target to gather an arbitrary number of middle or trailing values into a list.
first, *middle, last = (10, 20, 30, 40)
print(first)
print(middle)
print(last)10
[20, 30]
40Remember: The starred target is always a list, even when unpacking a tuple.
6 · Return multiple values
Returning comma-separated results from a function returns a tuple; callers can unpack it immediately.
def minimum_and_maximum(values):
return min(values), max(values)
low, high = minimum_and_maximum([6, 3, 8])
print(low, high)3 8Remember: For empty input, guard before calling min() and max().
7 · Tuple records and namedtuple
Use namedtuple for lightweight immutable records with named fields. For data plus behaviour, consider a class or dataclass.
from collections import namedtuple
Student = namedtuple('Student', 'name marks')
s = Student('Meera', 92)
print(s.name)
print(s[1])Meera
92Remember: Named tuples improve readability over unexplained numeric positions.
8 · Hashability and dictionary keys
A tuple is hashable only when every element is hashable. Tuples of strings and numbers are common composite dictionary keys.
sales = {('Varanasi', 2026): 150}
print(sales[('Varanasi', 2026)])
print(hash((1, 2)) == hash((1, 2)))150
TrueRemember: A tuple containing a list cannot be a dictionary key because that tuple is unhashable.
9 · Ordering, equality and choice
Tuples compare lexicographically: compare first differing items. Use a list when you need to add, remove or replace items, and a tuple for fixed records.
a = (2, 'Asha')
b = (3, 'Meera')
print(a < b)
print((1, 2) == (1, 2))True
TrueRemember: Only order tuples whose compared elements support ordering with one another.
10 · Mini-project: map co-ordinates
Represent locations as immutable coordinate pairs and calculate a Manhattan-style grid distance.
def grid_distance(a, b):
ax, ay = a
bx, by = b
return abs(ax - bx) + abs(ay - by)
home = (2, 3)
school = (7, 5)
print(grid_distance(home, school))7Remember: Extension: change the function to compute Euclidean distance using math.hypot().
Test your understanding
Predict or explain the answer before opening the solution. Try rewriting one of the examples without copying it.
1. How do you create a tuple with only the number 7?
Answer: (7,)
The comma matters.
2. Can a tuple containing a list be a dictionary key?
Answer: No, because the tuple is unhashable.
Every component needs to be hashable.
3. What type is rest in a, *rest = (1,2,3)?
Answer: list
Starred unpacking creates a list.
Take it further: expand the mini-project with an input() prompt, a reusable function, input validation and three tests (normal, empty and boundary cases).
When to use each Python collection
| Type | Ordered? | Mutable? | Duplicates? | Best for |
|---|---|---|---|---|
| str | Yes | No | Yes | Text |
| list | Yes | Yes | Yes | Changing sequences |
| tuple | Yes | No* | Yes | Fixed records |
| set | No guaranteed order | Yes | No | Unique membership |
| dict | Insertion order | Yes | Keys unique | Named lookups |
* A tuple itself cannot be reassigned, but a mutable item stored inside it can still change.
Programmer's Picnic · Developed and maintained by Champak Roy · Practice with real Python, one step at a time.