Learn Python
>>> functions.packing_unpacking

Packing and Unpacking in Python

#concept

Packing means collecting several values into one collection; unpacking means the reverse — spreading a collection's items back out into separate variables or arguments. Python does this constantly, often invisibly: multiple assignment, *args, and **kwargs are all forms of the same underlying idea.

#how it works
1

Packing

a, b, c = 1, 2, 3 assigns three separate values, packing the right-hand side into an implicit tuple first.

2

Unpacking a sequence

x, y = point spreads a two-item collection directly into two variables.

3

A starred variable captures the rest

first, *rest = [1, 2, 3, 4] gives first the value 1 and rest the list [2, 3, 4].

4

Unpacking into a function call

func(*my_list) spreads a list’s items out as separate positional arguments.

5

Unpacking a dictionary into keyword arguments

func(**my_dict) passes each key-value pair as its own keyword argument.

#example
first, *middle, last = [1, 2, 3, 4, 5]
print(first, middle, last)
 
coords = (3, 4)
 
def show(x, y):
print(f"x={x}, y={y}")
 
show(*coords)
Output
1 [2, 3, 4] 5
x=3, y=4
1first, *middle, last = [1, 2, 3, 4, 5] unpacks the list, giving first the first item, last the final item, and middle a list of everything in between.
2show(*coords) unpacks the tuple (3, 4) into two separate positional arguments, exactly as if show(3, 4) had been called directly.
#use cases
Splitting data into a 'first item' and 'the rest', like a header row and the data rows that follow it
Passing a list or tuple's items into a function that expects separate arguments, without unpacking manually one at a time
Merging two dictionaries into one using ** inside a new dictionary literal
Returning multiple values from a function and unpacking them directly into named variables at the call site

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.