Tuples

Intermediate · 18 min read · ▶ live playground · ✦ checkpoint

Sometimes a collection should feel locked. A player's name, score, and medal belong together, but you don't want random code adding a fourth piece halfway through. That is where a tuple fits: a small ordered collection for values that should travel together.

A tuple is a fixed ordered collection

A tuple is an ordered, immutable collection of values. Ordered means the items keep their positions, immutable means Python will not let you change the tuple's slots in place, and a collection is one object that holds many values.

Think of a tuple like a sealed index card. You can read each line on the card, and you can make a new card with updated facts, but you don't scribble over one slot on the old card.

player_card = ("Mina", 42, "gold")
empty_tuple = ()
 
print(player_card)
print(player_card[0])
print(player_card[-1])
print(player_card[0:2])
print(empty_tuple)

('Mina', 42, 'gold')
Mina
gold
('Mina', 42)
()

Tuple positions work like list positions from lesson 5.1. An index is a numbered position, so player_card[0] gets the first item. A negative index counts backward from the end. A slice takes a smaller tuple, using the same start-included and stop-excluded rule you already used with strings and lists.

Use tuples when the shape matters: one player card has name, score, medal; one map point has row, column; one color might have red, green, blue. That fixed shape is the point.

The comma makes the tuple

Parentheses help humans read tuples. For non-empty tuples, the comma is what makes the tuple; the empty tuple is the special case (). That detail matters most when the tuple has one item.

favorite_snack = ("mango")
snack_tuple = ("mango",)
loose_tuple = "tea", "dates"
 
print(favorite_snack)
print(snack_tuple)
print(loose_tuple)
print(type(favorite_snack))
print(type(snack_tuple))

mango
('mango',)
('tea', 'dates')
<class 'str'>
<class 'tuple'>

("mango") is just the string "mango" with grouping parentheses around it. ("mango",) is a single-element tuple, a tuple with exactly one item. Python prints the trailing comma back to you because without it, the display would be ambiguous.

The loose_tuple line shows the other side: "tea", "dates" is still a tuple even without parentheses. In beginner code, use parentheses for tuple literals unless the surrounding Python pattern makes the tuple obvious. Clear beats clever.

Tuples do not change in place

Tuple immutability is the same promise you saw with strings: you can read a position, but you cannot assign into that position. If you try player_card[1] = 43, Python raises TypeError: 'tuple' object does not support item assignment.

When a fact changes, build a new tuple and move the name tag to it. The old tuple is not patched.

player_card = ("Mina", 42, "gold")
updated_card = (player_card[0], player_card[1] + 1, player_card[2])
 
print(player_card)
print(updated_card)
 
player_card = updated_card
print(player_card)

('Mina', 42, 'gold')
('Mina', 43, 'gold')
('Mina', 43, 'gold')

That last assignment does not break immutability. It moves the name player_card to a new tuple object, just like the name-tag model from lesson 2.1.

One nuance: immutability protects the tuple's slots, not every object inside those slots. If a tuple holds a list, the tuple still points at the same list, and that list can change. For beginner tuples, prefer values you mean to treat as fixed.

Packing and unpacking

Packing means bundling several values into one tuple. Unpacking means assigning items from a collection into several names at once.

match_result = ("Noor", 18, "win")
player, points, result = match_result
 
print(match_result)
print(player)
print(points)
print(result)

('Noor', 18, 'win')
Noor
18
win

The left side has three names. The tuple has three items. Python matches them by position: first to first, second to second, third to third.

Unpacking is common because tuples often represent records, small bundles of related facts about one thing. Once a record lands in your code, unpacking gives each fact a clear name.

Try it - unpack a score card

Change the values, then run again. Keep the number of names on the left matched to the number of tuple items on the right.

python — playgroundlive
⌘/Ctrl + Enter to run

Preview: returning multiple values

A function is a reusable block of code that you call by name; defining your own functions gets its full treatment in lesson 7.1. This is only a preview because tuples explain a Python pattern you will see everywhere: returning multiple values.

A return value is the value a function sends back to the code that called it. When a function appears to return several values, Python is really returning one tuple, and the caller often unpacks it right away.

def read_score_line(line):
    player, score_text = line.split(":")
    return player, int(score_text)
 
player, score = read_score_line("Mina:42")
 
print(player)
print(score)

Mina
42

Do not worry about the def line yet. The shape to notice is the last line inside the function: return player, int(score_text). That comma creates a tuple. The call then unpacks that tuple into player and score.

A peek at named tuples

A named tuple is a tuple whose positions also have names. It still behaves like a tuple, but you can read fields with dots instead of remembering every position.

from collections import namedtuple
 
PlayerCard = namedtuple("PlayerCard", ["name", "score", "medal"])
card = PlayerCard("Ravi", 31, "bronze")
 
print(card)
print(card[0])
print(card.name)
print(card.score)

PlayerCard(name='Ravi', score=31, medal='bronze')
Ravi
Ravi
31

The first line uses an import, a statement that borrows code from a module, an importable bundle of reusable names and tools. Imports get their full story in lesson 8.1, and collections is part of the standard library, the tools that ship with Python, which you will tour in lesson 8.2.

A field is a named piece of a record. Here the fields are name, score, and medal. card[0] still works, but card.name tells the story better.

Named tuples are a beginner-friendly peek, not the final record tool. Dictionaries arrive in lesson 6.1, functions in 7.1, and classes, a richer way to design your own kinds of objects, arrive in lesson 10.2.

Checkpoint

Answer all three to mark this lesson complete

Tuples give you fixed, ordered records: light enough to write quickly, strict enough to keep a shape steady. Next, you will use loops and transformation tools to work with whole collections cleanly instead of handling one item at a time.

+50 XP on completion