Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 149 ยท Data Structures

Unpacking and Star Expressions

Learn Python unpacking. Split sequences into variables, grab the rest with a star, ignore values with _, and spread lists and dicts with * and ** in calls and literals.

Unpacking means taking a collection apart and giving each piece its own name, in one statement. You've already seen the simple form with tuples: x, y = (3, 7). Python takes that idea much further. A star (*) can collect "everything else", unpacking works inside loops and nested structures, and the same * and ** symbols can spread a list or a dictionary into a function call or a new collection.

These features turn awkward index juggling such as first = items[0] and rest = items[1:] into short, self-explaining lines. They also show up constantly in real Python code, so learning to read them pays off quickly.

Basic unpacking

Put several names on the left of = and any iterable on the right. Python assigns the items in order:

Python Unpacking any iterable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Anything you can loop over can be unpacked: tuples, lists, strings, ranges, dictionary views, map() results and more. The only rule is that the number of names must match the number of items.

When the counts don't match

If there are too many or too few values, Python raises a ValueError that tells you exactly what went wrong:

Python Count mismatches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

That strictness is a feature: if your data has an unexpected shape, you find out immediately instead of silently getting wrong values. Imagine reading lines like "Ana,31" from a file and one line says "Ben,27,Oslo". Code that unpacks name, age = line.split(",") stops right at the bad line, while code that grabs parts[0] and parts[1] quietly ignores the extra field.

Star expressions: collecting the rest

Put a * before one name and it collects every item that the other names don't take, as a list:

Python Using *rest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Some rules for star targets:

  • Only one starred name is allowed per assignment; two would be ambiguous.
  • The starred name always gets a list, even when unpacking a tuple or string, and it may be empty.
  • You still need enough items for the non-starred names: a, b, *rest = [1] raises ValueError.

Tip: Star unpacking reads better than slicing when you need both parts. Compare first, *rest = items with first = items[0] and rest = items[1:]. The unpacking version also works on any iterable, not only on sequences that support indexing.

Ignoring values with _

When you need only some of the values, assign the rest to _. It's a normal variable name, but by convention it means "I don't care about this":

Python
name, _, price = ("Lamp", "SKU-221", 39.99)
year, *_ = "2026-10-14".split("-")      # keep only the year

Unpacking function results

Functions often return several related values as a tuple, and unpacking is the natural way to receive them. Built-in functions do this too: divmod(17, 5) returns (3, 2), the quotient and the remainder, and you'll usually see it unpacked straight away:

Python
minutes, seconds = divmod(250, 60)          # 4, 10
name, _, extension = "report.final.pdf".rpartition(".")

str.rpartition() returns a three-item tuple: everything before the last separator, the separator itself and everything after it. The underscore discards the middle part. Unpacking right at the call site gives every piece a meaningful name immediately, which is much clearer than passing result[0] and result[2] around your program. You'll write your own multi-value functions in Return Values.

Nested unpacking and loops

The left side can mirror the structure of the data, including nested tuples and lists. This shines in for loops, where each item is unpacked as it arrives:

Python Unpacking in loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The parentheses in (lat, lon) and (student, grade) tell Python to unpack that inner pair too. enumerate() produces (index, item) pairs, and here each item is itself a (key, value) pair from items(), so the pattern nests one level.

* in function calls

The star also works in the opposite direction. In a function call, *iterable spreads the items out as separate positional arguments:

Python Spreading arguments with *

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

area(*size) is the same as area(800, 600). This is handy whenever your data is already in a list or tuple but the function expects separate arguments.

** in function calls

Two stars spread a dictionary into keyword arguments. Each key becomes a parameter name, and each value becomes that parameter's argument:

Python Spreading keyword arguments with **

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The keys must match the function's parameter names, or Python raises a TypeError. Functions can also collect arguments with *args and **kwargs in their definition; that's the topic of Arguments: Defaults, *args and **kwargs.

* and ** in literals

You can spread items into new lists, tuples and sets with *, and spread dictionaries into a new dictionary with **. It's a concise way to combine collections:

Python Building collections by unpacking

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a dictionary literal, later keys win, so {**defaults, **user} lets the user's values override the defaults. Since Python 3.9 you can write the same merge as defaults | user, as shown in Dictionary Methods. Both forms create a new dictionary and leave the originals unchanged.

Note: A single star on a dictionary spreads only its keys: [*{"a": 1, "b": 2}] gives ['a', 'b']. You need two stars to work with key-value pairs, and ** only works inside dictionary literals and function calls.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After first, *rest = (10, 20, 30), what is rest?

    A starred target always receives a list, even when the source is a tuple.
  2. 2. What does a, b = [1, 2, 3] do?

    Without a starred name, the counts must match exactly. Use a, *b = [1, 2, 3] to collect the rest.
  3. 3. With nums = [5, 1, 8], what does print(*nums) print?

    *nums spreads the list into three separate arguments, and print() separates them with spaces.
  4. 4. What is {**{"a": 1, "b": 2}, **{"b": 3}}?

    Both dictionaries are spread into a new one, and the later value for a repeated key wins.
  5. 5. How many starred names can appear on the left side of one assignment?

    Two starred names would be ambiguous, so Python allows only one per unpacking target.

Summary

  • Unpacking assigns each item of any iterable to its own name: x, y = point. The counts must match.
  • A starred name collects the leftover items as a list: first, *rest = items. Only one star per assignment.
  • Use _ for values you want to ignore, and parentheses to unpack nested data, especially in for loops.
  • In calls, *seq spreads items as positional arguments and **mapping spreads key-value pairs as keyword arguments.
  • In literals, [*a, *b] and {*a, *b} combine iterables, and {**d1, **d2} merges dictionaries with later keys winning.

Next: Arrays with the array Module.