Python Tuples · Examples
Beginner

Python Tuples Examples

Short, runnable programs that show python tuples in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Tuples lesson.

1Looping over a list of tuples

Each order is a fixed (item, quantity, price) record. Unpacking in the for line gives every field a name.

Looping over a list of tuples
orders = [("pen", 3, 1.20), ("notebook", 2, 3.50), ("bag", 1, 15.00)]
total = 0
for item, qty, price in orders:
    cost = qty * price
    total += cost
    print(f"{item}: {qty} x {price:.2f} = {cost:.2f}")
print(f"Total: {total:.2f}")
Expected outputpen: 3 x 1.20 = 3.60
notebook: 2 x 3.50 = 7.00
bag: 1 x 15.00 = 15.00
Total: 25.60

2Collecting the rest with *

A starred name in an unpacking collects all the leftover items into a list, so the counts no longer have to match exactly.

Collecting the rest with *
scores = (98, 91, 85, 77, 60)
best, *middle, worst = scores
print("Best:", best)
print("Worst:", worst)
print("Middle:", middle)
Expected outputBest: 98
Worst: 60
Middle: [91, 85, 77]

3Tuples compare item by item

Python compares tuples position by position, stopping at the first difference. That makes (year, month, day) tuples sort into date order.

Tuples compare item by item
print((1, 9) < (2, 0))
print((2024, 5, 1) < (2024, 4, 30))
deadlines = [(2024, 12, 1), (2024, 3, 15), (2023, 11, 30)]
print(sorted(deadlines))
Expected outputTrue
False
[(2023, 11, 30), (2024, 3, 15), (2024, 12, 1)]

4Counting and finding with count() and index()

Tuples have only two methods, and neither changes the tuple: count() and index().

Counting and finding with count() and index()
votes = ("yes", "no", "yes", "yes", "abstain")
print("yes votes:", votes.count("yes"))
print("first no at index", votes.index("no"))
print("maybe" in votes)
Expected outputyes votes: 3
first no at index 1
False

Practise next

Python Tuples exercises → Back to the lesson

Python Lists examplesPython Unpacking examplesPython Sets examplesPython Dictionaries examples