Lesson 30 of 60
โฎPrev Nextโฏ

PY-101 ยท Collections

Unpacking

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

30of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก 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.

    Unpacking, running
    1. name, city = ("Asha", "Pune")
    2. print(name, "lives in", city)
    3. first, *rest = [90, 85, 70, 60]
    4. print(first, rest)
    5. for place, runner in enumerate(["Li", "Sam"], start=1):
    6. print(place, runner)
    7. for item, price in zip(["tea", "milk"], [40, 30]):
    8. print(item, price)
    Press โ–ถ to watch Python run this, one line at a time.
    1. 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.
    2. The Python ideaa, b = pairUnpacking assigns the items of a sequence to several variables at once: name, age = ("Asha", 29).
    3. 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): ...

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    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].

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. a, b = 1, 2; a, b = b, a. What is a?
    2. 2. first, *rest = [1, 2, 3]. What is rest?
    3. 3. What does enumerate give in each loop round?
    4. 4. list(zip([1, 2], ["a", "b"]))?
    5. 5. x, y = [1, 2, 3] raises?

    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