PY-101 ยท Collections
Unpacking
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
Unpacking assigns the items of a sequence to several variables at once: name, age = ("Asha", 29). A starred name collects whatever is left, as in first, *rest = scores. It is how Python swaps values, loops over pairs and reads several return values neatly.
- Unpack into several variables
- Collect the rest with *
- Loop with enumerate and zip
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
name, city = ("Asha", "Pune")print(name, "lives in", city)first, *rest = [90, 85, 70, 60]print(first, rest)for place, runner in enumerate(["Li", "Sam"], start=1):print(place, runner)for item, price in zip(["tea", "milk"], [40, 30]):print(item, price)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
Asha lives in Pune
90 [85, 70, 60]
1 Li
2 Sam
tea 40
milk 30 ๐ฏ Use zip to pair names with marks and print one line per student like: Asha: 91
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
for n, m in zip(names, marks): print(f"{n}: {m}")
- The problemA function returns a student's name, class and score. Reading result[0], result[1], result[2] is hard to follow. Unpacking gives each one a real name.
- The Python idea
a, b = pairUnpacking assigns the items of a sequence to several variables at once: name, age = ("Asha", 29). - In real lifeReading a CSV row as id, name, email = row makes the next 20 lines of code readable instead of full of row[2].
Start with a question
A function returns a student's name, class and score. Reading result[0], result[1], result[2] is hard to follow. Unpacking gives each one a real name.
Clean code gives values names. Unpacking appears in loops, function returns and almost every Python codebase.
Explain it like I'm 10
Unpacking is opening a parcel and putting each thing straight into its own place: shoes on the shelf, book on the desk.
The technical explanation
a, b = b, a swaps two values in one line.
first, *middle, last = [1, 2, 3, 4] gives first=1, middle=[2, 3], last=4.
for i, name in enumerate(names): and for a, b in zip(list1, list2): both unpack pairs in the loop.
Syntax
a, b = pair
first, *rest = items
for i, x in enumerate(items): ... Real-world scenario
Reading a CSV row as id, name, email = row makes the next 20 lines of code readable instead of full of row[2].
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Sorting and searching โQuestions people ask
What does the star mean in a, *b = items?
It collects all remaining items into a list. Only one name per assignment can have a star.
What happens when zip lists have different lengths?
zip stops at the shortest list. Use itertools.zip_longest to keep going and fill the gaps.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What does the star mean in a, *b = items?
It collects all remaining items into a list. Only one name per assignment can have a star.
beginner What happens when zip lists have different lengths?
zip stops at the shortest list. Use itertools.zip_longest to keep going and fill the gaps.
intermediate a, b = 1, 2; a, b = b, a. What is a?
2. The values swap.
intermediate first, *rest = [1, 2, 3]. What is rest?
[2, 3]. The starred name collects a list.
Quick revision
Remember
- Unpack into several variables
- Collect the rest with *
- Loop with enumerate and zip
- The number of names must match the number of items, unless one name has a star. Otherwise you get "too many values to unpack".
Syntax
a, b = pair
first, *rest = items
for i, x in enumerate(items): ... Official documentation
- enumerate() and zip() (docs.python.org)