Programming Search⌘K

Featurecore

Unpacking in lists and list comprehensions

Also called star in a list display, iterable unpacking in a list, unpacking in comprehensions, flatten with star, PEP 798, Value after * must be an iterable.

A * before an item of a list, tuple or set display adds the items of an iterable. A starred expression in a list or set comprehension, and ** in a dict comprehension, joins iterables or dicts.

Language
Python

Synopsis

x = [1, 2, 3]
print([0, *x, 4, 5, 6])
print((*"ab", *range(2)))
print({*x, *[3, 4]} == {1, 2, 3, 4})
Output
[0, 1, 2, 3, 4, 5, 6]
('a', 'b', 0, 1)
True

Each starred item adds all the items of its iterable at that place in the new container.

Semantics

r1. "For tuple, list and set (but not dict) displays, any item in the display may be prefixed with an asterisk (*). This denotes iterable unpacking. At runtime, the asterisk-prefixed expression must evaluate to an iterable, whose contents are inserted into the container at the location of the unpacking."2 Example: display.

r2. "This only works if the expression following the * evaluates to an iterable object; trying to unpack a non-iterable object will raise an exception".1 Example: not-iterable.

r3. "If the expression of a list or set comprehension is starred, the result will be unpacked to produce zero or more elements."2 The comprehension is roughly a loop that calls result.extend(people) for each item.2 Example: flatten.

r4. "In dict comprehensions, a double-starred expression will be evaluated and then unpacked using dictionary unpacking, inserting zero or more key/value pairs into the new dictionary."2 Example: merge-dicts.

r5. PEP 798 extends "list, set, and dictionary comprehensions, as well as generator expressions, to allow unpacking notation (* and **) at the start of the expression".3 Unpacking in displays came earlier, from PEP 448.4

Examples

x = [[1, 2, 3], [4, 5, 6], [], [7], [8, 9]]
print([*element for element in x])

mixed = [[1, 2], "cat", {"spam": "eggs"}]
print([*element for element in mixed])
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 'c', 'a', 't', 'spam']

Each item of x is unpacked into the new list (rule r3). A dict gives its keys.

system_defaults = {"color": "blue", "count": 8}
user_defaults = {"color": "yellow"}
overrides = {"count": 5}
configuration_sets = [system_defaults, user_defaults, overrides]
print({**d for d in configuration_sets})
Output
{'color': 'yellow', 'count': 5}

A later dict replaces the value of a key that an earlier dict set (rule r4).

fruits = [{"apple", "avocado"}, {"banana"}, {"apple"}]
print(sorted({*group for group in fruits}))
Output
['apple', 'avocado', 'banana']
x = [[1, 2, 3], [4, 5, 6], [], [7], [8, 9]]
print([n for element in x for n in element])
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Two for clauses give the same flat list, and this form also works before Python 3.15 (rule r5).

Pitfalls

A starred item must be an iterable:

This code raises TypeError, on purpose.

x = 1
items = [0, *x, 2, 3, 4]

Write [0, x, 2, 3, 4] to add the value itself (rule r2).

A dict display cannot use a single *. Use ** for a mapping, and * only in tuple, list and set displays (rule r1).

Comparison

Go has no unpacking in a slice literal. A Go program joins slices with append and the ... form: "If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array that fits both the existing slice elements and the additional values."5 So append(append([]int{0}, x...), 4, 5, 6) gives the same values as the Python display [0, *x, 4, 5, 6] (rule r1).

References

  1. The Python Tutorial, 5. Data Structures, 5.1.5. Unpacking in Lists and List Comprehensions
  2. The Python Language Reference, Python 3.15, 6.2.5. Container displays; 6.2.6.3. Unpacking in comprehensions
  3. PEP 798: Unpacking in Comprehensions, Abstract
  4. PEP 448: Additional Unpacking Generalizations, Abstract
  5. The Go Programming Language Specification, Appending to and copying slices

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source