Skip to content
dreamcode
dreamcode
Map
Unpacking
Lesson 35 of 77
+15 XP on finish
PYTHON INTERMEDIATEChapter 6 · Comprehensions and data tools

Unpacking values

Unpacking assigns several variables at once from a sequence: x, y = (3, 4). It is how you swap two values in one line (a, b = b, a) and how a function hands back more than one result. A starred name collects whatever is left: first, *rest = [1, 2, 3].

Worked example

How it reads

  • The number of names on the left must match the number of values
  • return a, b returns a tuple, which you unpack straight away
  • *middle soaks up the values in between as a list
Common mistakes
  • x, y = [1, 2, 3] raises ValueError: too many values to unpack.
Cloud tip: Unpacking works in loops too: for name, mag in pairs: unpacks each pair as you go.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Unpack the result into total and count, then print the average: 6.0.

Press Run to check your work.