Tuples and unpacking

Lists & Tuples, lesson 6 of 6

📋 Lists & Tuples, lesson 6 of 6

Tuples and unpacking

Group fixed values in tuples and unpack them into variables.

9 min

1 exercise

3 quizzes

0/4 solved

Getting Python ready… examples can run in a moment.

A tuple is like a list that can't change (immutable). Write it with parentheses: point = (3, 4). Use tuples for small, fixed groups: coordinates, RGB colors, a (name, score) pair. Indexing, slicing, len and in all work.

Example

Points and colors

Make your own color tuple, e.g. (0, 128, 255).

Example

Tuples can't change

To "change" a tuple, make a new one: point = (10, point[1]).

Quiz

What does this print?

Unpacking assigns each item to its own variable in one go: x, y = point. The number of names must match the number of items, unless you use a starred name (*rest) to collect the leftovers.

It also gives Python its famous one-line swap: a, b = b, a.

Example

Unpacking tricks

Try *others, last = [...] to grab the last item instead.

Example

Loop over pairs

Each tuple is unpacked into name and score on every pass.

Quiz

What does this print?

Exercise

Trip planner

trip lists (city, nights) tuples. Loop over it with unpacking (for city, nights in trip:) to:

  1. Add up all nights in total_nights.
  2. Store the city with the most nights in longest.
Quiz

When is a tuple a better choice than a list?