Skip to contentSkip to navigation

Module 03 · Lesson 02

Tuples & Sequence Unpacking

Group values that belong together with tuples, which cannot be changed, and take them apart again with unpacking, including the star form for the rest.

  • About 8 minutes
  • Beginner friendly
  • 12-question quiz at the end

What you will learn

  • Make a tuple
  • Unpack in one line
  • Collect with a star
  • Tuple or list

Values that belong together

A tuple is a small, fixed group of values, like the two numbers of a map position.

  • Make one

    Commas make a tuple: point = (3, 5). The brackets just make it easy to see.

  • Fixed

    Once made, a tuple cannot change. No adding, removing or swapping items.

  • Unpack

    x, y = point hands each value to its own name in one line.

  • Star

    first, *rest = scores puts the first value in first and all the others in a list called rest.

Fixed groups all around

Some values always travel together and should never be mixed up.

  • Map pinsA place is a latitude and a longitude, always as a pair.
  • ColoursScreens mix red, green and blue: orange is (255, 165, 0).
  • Dates(2026, 11, 28) keeps year, month and day in a fixed order.
  • Screen sizesA screen is (1920, 1080): width first, then height.

Unpacking in one line

One line, two new names. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

first name:Gets the first value of the tuple, 3.

Pack and unpack

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Make one

Indexes and len() work just like on a list.

Your turn: Make a 3D point with x, y and z, and print only z.

Python
point = (3, 5)
print(point)
print(point[0], point[1])
print(len(point))
Output
Press Run to see what it prints.

Watch values unpack

Press Step to run one line at a time. Watch new names appear from one tuple.

Ready. Press Step to run the first line.

  1. size = (1920, 1080)
  2. width, height = size
  3. pixels = width * height
  4. colour = (255, 165, 0)
  5. red, *rest = colour
  6. print(f"{pixels:,} pixels")
  7. print(red, rest)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Slicing a tuple: what prints?

t = (1, 2, 3)
print(t[1:])

0 of 6 answered

Common tuple misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Fixed groups of values

A tuple is an ordered collection, like a list, written with round brackets instead of square ones.

Try it 1: edit me, then Run
point = (3, 5)
person = ("Ivy", 12, "Leeds")
print(point[0], person[-1], len(person))
Output
Press Run to see what it prints.

Indexing, negative indexes, slicing, len(), in and looping all work exactly as they do for lists. This prints 3 Leeds 3.

The brackets are often optional. Python makes a tuple whenever values are separated by commas, which is called packing: size = 1920, 1080 is the same as size = (1920, 1080). Brackets are still a good idea for clarity, and they are required inside a function call.

The one-item tuple

Round brackets are also used for grouping in maths, so ("hi") is just the string "hi". To make a tuple with one item you need a trailing comma: ("hi",). It looks odd, but it is the comma, not the brackets, that makes a tuple. An empty tuple is ().

Try it 2: edit me, then Run
print(type(("hi")))     # <class 'str'>
print(type(("hi",)))    # <class 'tuple'>
Output
Press Run to see what it prints.

Immutable

The big difference from a list is that a tuple is immutable: once created, it cannot be changed. There is no append, remove or sort, and assigning to an index fails.

Try it 3: edit me, then Run
point = (3, 5)
point[0] = 4        # TypeError: 'tuple' object does not support item assignment
Output
Press Run to see what it prints.

To "change" a tuple you build a new one, for example point = (4, point[1]). The name now refers to a different tuple; the old one was never modified. Tuples have just two methods: count(value) and index(value).

Immutability is a feature, not a limitation. If a function receives a tuple, it cannot break the caller's data by changing it. Tuples are also slightly smaller and faster than lists, and, because they never change, they can be used as dictionary keys, which you will see in the dictionaries lesson.

One subtlety: a tuple that contains a list cannot swap that list for another, but the list itself can still be changed. t = ([1], 2) followed by t[0].append(9) works. The tuple still holds the same list; it is the list that changed.

Unpacking

Unpacking is the reverse of packing: it assigns each item of a tuple to its own name in one line. The number of names must match the number of items.

Try it 4: edit me, then Run
city = ("Paris", "France", 2_100_000)
name, country, population = city
print(name, country)
Output
Press Run to see what it prints.

Unpacking works with any sequence, including lists and strings. It is what makes a, b = b, a swap two values: the right side is packed into a tuple, then unpacked into the left side. If the counts do not match, Python raises ValueError: too many values to unpack or not enough values to unpack.

Star unpacking

A name with a star in front collects every item that the other names do not take, as a list. Exactly one starred name is allowed.

Try it 5: edit me, then Run
first, *middle, last = (1, 2, 3, 4, 5)
print(first, middle, last)      # 1 [2, 3, 4] 5
head, *rest = "abc"
print(head, rest)               # a ['b', 'c']
Output
Press Run to see what it prints.

When you need a position in an unpacking but not the value, the convention is to name it _: name, _, population = city.

Tuples in loops

A list of tuples is a common way to hold a table of records, and unpacking in the loop header gives each column a name.

Try it 6: edit me, then Run
results = [("Ana", 82), ("Bo", 95), ("Cy", 77)]
for name, score in results:
    print(f"{name}: {score}")
Output
Press Run to see what it prints.

Tuples compare item by item, from the left. (1, 9) < (2, 0) is True because 1 is less than 2, and the second items are only compared when the first ones are equal. That means sorting a list of tuples sorts by the first item, then by the second, which is often exactly what a report needs.

Moving between tuples and lists

list(t) turns a tuple into a new list you can change, and tuple(items) freezes a list into a tuple. A common pattern is to receive a tuple, convert it to a list, change it, and convert it back only if a fixed record is needed again. Built-in functions that only read, such as len(), min(), max(), sum() and sorted(), work on tuples directly; sorted() always gives back a list, whatever it was given.

Tuple or list?

Use a tuple for a fixed record whose parts have different meanings: a date (2024, 6, 15), a colour (255, 128, 0), coordinates. Use a list for a collection of similar things that may grow, shrink or be sorted: the scores in a game, the items in a basket. A good test is to ask whether swapping two items would change the meaning. In ("Ivy", 12) it would; in a list of scores it would not.

Syntax

The general shape of the statements in this lesson.

syntax.py
point = (3, 5)        size = 1920, 1080    # packing
single = ("hi",)      empty = ()           # one item needs a comma
point[0]   point[-1]  point[1:]   len(point)
point.count(3)        point.index(5)
x, y = point                               # unpacking
first, *rest = (1, 2, 3)                   # rest is [2, 3]
a, b = b, a                                # swap
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Distances from a list of coordinates

Beginner

Given a few map points as (x, y) tuples, print each point and how far it is from the origin along the grid (the sum of the absolute values).

Python
points = [(3, 4), (-2, 5), (0, -6)]
for x, y in points:
    distance = abs(x) + abs(y)
    print(f"({x}, {y}) is {distance} blocks away")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Each point is a tuple because its two parts mean different things and should never change separately. Unpacking in the loop header gives them readable names. abs() is a built-in function that drops a minus sign.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Forgetting the comma in a one-item tuple

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
colours = ("red")
print(len(colours))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints 3, the length of the string red

Write this instead

colours = ("red",)
print(len(colours))

Why it happens

Brackets alone only group. Without a comma, ("red") is the string itself.

In the real world

Where this shows up in software people use every day.

  1. Opening hours for a week

    Retail

    A bakery's website stores its opening hours as one tuple per day, so the times for a day always stay together and cannot be edited by accident.

    Why Python fits

    Each day is a fixed record of three parts, which is exactly what a tuple is for. The list holds the days because the bakery might add or remove a day later.

    Python
    hours = [("Mon", 7, 15), ("Tue", 7, 15), ("Sat", 8, 13), ("Sun", 0, 0)]
    for day, opens, closes in hours:
        if opens == closes:
            print(f"{day}: closed")
        else:
            print(f"{day}: {opens}:00 to {closes}:00 ({closes - opens} h)")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

How do I add an item to a tuple?

You cannot change it, but you can build a new one: t = t + (4,). If you do this often, a list is the better choice.

Can I turn a list into a tuple?

Yes, tuple([1, 2]) gives (1, 2), and list((1, 2)) goes the other way.

Why does a function return a tuple?

return a, b packs two values into a tuple, and the caller can unpack them: low, high = limits(). The functions lesson covers this.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 7 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.