Python 3.0+Lists (list)term
List unpacking — *
unpacking
Unpacking assigns the items to variables. * captures the rest as a list.
Syntax
a, b, *rest = lst | *head, last = lst | a, *_, b = lst
Without a star the number of names on the left must match the number of items exactly, otherwise you get a ValueError such as "not enough values to unpack"; the star lifts that restriction, but only one star is allowed per target. The starred name always ends up holding a list, even when the right side is a tuple or a string, and even when there is nothing left to capture (then it is empty).
Examples
a, b, c = [1, 2, 3]
print(a, b, c)
# → 1 2 3
first, *rest = [1, 2, 3, 4, 5]
print(first, rest)
# → 1 [2, 3, 4, 5]
*head, last = [1, 2, 3, 4, 5]
print(head, last)
# → [1, 2, 3, 4] 5
a, *_, b = [1, 2, 3, 4, 5]
print(a, b)
# → 1 5
lst1, lst2 = [1, 2, 3], [4, 5]
combined = [*lst1, *lst2]
print(combined)
# → [1, 2, 3, 4, 5]
def func(*args): return sum(args)
nums = [1, 2, 3]
print(func(*nums))
# → 6
See also
Open in the full glossarydocs.python.orgReport an inaccuracy