Programmer's Picnic · Python Foundations · 0 → ∞

Python Tuples: From 0 to Infinity

Make reliable fixed-size records and unpack them into readable code.

Free course · 45–65 minutes reading and practice · No installation beyond Python 3

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.

Level 0 / 10

0 · Meet the tuple

A tuple is an ordered sequence whose positions cannot be reassigned. It can contain duplicate items and different types.

Python 3 · runnable example
person = ('Asha', 21, 'Varanasi')
print(person)
print(type(person).__name__)
print(person[0])
Expected output
('Asha', 21, 'Varanasi')
tuple
Asha

Remember: The comma, not just the parentheses, creates a tuple in most expressions.

Level 1 / 10

1 · Zero and one-element tuples

An empty tuple uses (). A one-element tuple needs a trailing comma. Parentheses alone group expressions.

Python 3 · runnable example
empty = ()
one = ('Python',)
not_a_tuple = ('Python')
print(type(one).__name__)
print(type(not_a_tuple).__name__)
print(len(empty))
Expected output
tuple
str
0

Remember: You can also write one = 'Python', but parentheses improve readability.

Level 2 / 10

2 · Index, slice and membership

Tuples follow the same indexing and slicing rules as lists and strings. Slicing creates a new tuple.

Python 3 · runnable example
colours = ('red', 'green', 'blue', 'green')
print(colours[-1])
print(colours[:2])
print(colours.count('green'))
print(colours.index('blue'))
Expected output
green
('red', 'green')
2
2

Remember: Use in before index() if the target may be missing.

Level 3 / 10

3 · Understand immutability

A tuple cannot be resized or assigned to by index. However, a mutable object inside a tuple can still change.

Python 3 · runnable example
record = ('Asha', ['Python'])
record[1].append('SQL')
print(record)
# record[0] = 'Ravi'  # TypeError
Expected output
('Asha', ['Python', 'SQL'])

Remember: Immutable container does not mean recursively immutable content.

Level 4 / 10

4 · Packing and unpacking

Put values together in a tuple (packing), then assign them to multiple names (unpacking). The number of destinations must match.

Python 3 · runnable example
point = (4, 9)
x, y = point
print(x, y)
a, b = (1, 2)
a, b = b, a
print(a, b)
Expected output
4 9
2 1

Remember: Use simple x, y = point; for swapping two values, write a, b = b, a.

Level 5 / 10

5 · Starred unpacking

Use one starred target to gather an arbitrary number of middle or trailing values into a list.

Python 3 · runnable example
first, *middle, last = (10, 20, 30, 40)
print(first)
print(middle)
print(last)
Expected output
10
[20, 30]
40

Remember: The starred target is always a list, even when unpacking a tuple.

Level 6 / 10

6 · Return multiple values

Returning comma-separated results from a function returns a tuple; callers can unpack it immediately.

Python 3 · runnable example
def minimum_and_maximum(values):
    return min(values), max(values)

low, high = minimum_and_maximum([6, 3, 8])
print(low, high)
Expected output
3 8

Remember: For empty input, guard before calling min() and max().

Level 7 / 10

7 · Tuple records and namedtuple

Use namedtuple for lightweight immutable records with named fields. For data plus behaviour, consider a class or dataclass.

Python 3 · runnable example
from collections import namedtuple
Student = namedtuple('Student', 'name marks')
s = Student('Meera', 92)
print(s.name)
print(s[1])
Expected output
Meera
92

Remember: Named tuples improve readability over unexplained numeric positions.

Level 8 / 10

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.

Python 3 · runnable example
sales = {('Varanasi', 2026): 150}
print(sales[('Varanasi', 2026)])
print(hash((1, 2)) == hash((1, 2)))
Expected output
150
True

Remember: A tuple containing a list cannot be a dictionary key because that tuple is unhashable.

Level 9 / 10

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.

Python 3 · runnable example
a = (2, 'Asha')
b = (3, 'Meera')
print(a < b)
print((1, 2) == (1, 2))
Expected output
True
True

Remember: Only order tuples whose compared elements support ordering with one another.

Level 10 / 10

10 · Mini-project: map co-ordinates

Represent locations as immutable coordinate pairs and calculate a Manhattan-style grid distance.

Python 3 · runnable example
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))
Expected output
7

Remember: Extension: change the function to compute Euclidean distance using math.hypot().

Practice lab

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

Comparison of Python built-in data types
TypeOrdered?Mutable?Duplicates?Best for
strYesNoYesText
listYesYesYesChanging sequences
tupleYesNo*YesFixed records
setNo guaranteed orderYesNoUnique membership
dictInsertion orderYesKeys uniqueNamed lookups

* A tuple itself cannot be reassigned, but a mutable item stored inside it can still change.

Python official built-in types reference ↗

Programmer's Picnic · Developed and maintained by Champak Roy · Practice with real Python, one step at a time.