Glossary

Unpacking

Unpacking (also called destructuring) is a syntax for assigning the elements of an iterable to multiple variables in a single statement. The basic form is a, b, c = [1, 2, 3], which assigns 1 to a, 2 to b, and 3 to c. Unpacking works with any iterable: tuples, lists, strings, generators, and any custom iterable.

Extended unpacking (PEP 3132) uses the * operator to capture "the rest" of the elements: first, *rest = [1, 2, 3, 4] gives first = 1 and rest = [2, 3, 4]. The starred variable can appear anywhere: *head, last = [1, 2, 3, 4] gives head = [1, 2, 3] and last = 4. This is extremely useful for processing variable-length sequences.

Unpacking enables several Pythonic idioms: swapping variables (a, b = b, a), iterating over dictionaries (for key, value in d.items()), returning multiple values from functions (x, y = get_coordinates()), and destructuring nested structures ((a, b), c = [1, 2], 3). At the call site, * unpacks iterables into positional arguments and ** unpacks dictionaries into keyword arguments, complementing the *args/**kwargs syntax in function definitions.

Related terms: Tuple, Function, Argument

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.