Python Packing and Unpacking

In the last lesson, we learned about Python Tuple Operations. Now let’s pack several values together and unpack them into variables.

Let’s Talk About Putting Things In and Taking Them Out

We have a tuple. Maybe it has a few values.

point = (10, 20)

We want to get those values out and into separate variables. We could do this:

x = point[0]
y = point[1]

That works. But it is a bit clunky. We have to use indices. And if the tuple is long, it gets tedious.

Python has a much nicer way. It is called unpacking.

And the reverse β€” putting multiple values into a tuple β€” is called packing. Let’s look at both.

Packing in Python

Packing is when we put multiple values into a single tuple. We do it without even thinking about it.

point = 10, 20

Here, 10 and 20 are packed into a tuple. That is packing.

We can also do it explicitly with parentheses.

point = (10, 20)

Both are the same. The comma is what makes the tuple. The parentheses are just for clarity.

We can pack any number of values.

person = "Alex", 25, "London"
print(person)

Output

('Alex', 25, 'London')

So packing is just creating a tuple from multiple values. We do it all the time.

Unpacking in Python

Unpacking is the opposite. We take a tuple (or list) and assign its items to separate variables in one go.

point = (10, 20)
x, y = point
print(x)
print(y)

Output

10
20

That is unpacking. The tuple (10, 20) is unpacked into x and y.

The number of variables on the left must match the number of items in the tuple. If they do not match, we get an error.

point = (10, 20, 30)
x, y = point # Error!

Output

ValueError: too many values to unpack (expected 2)

So we have to match them exactly. Unless we use the star operator, which we will see in a moment.

Unpacking Works with Lists Too

We can unpack lists the same way.

numbers = [1, 2, 3]
a, b, c = numbers
print(a, b, c)

Output

1 2 3

It works with any iterable, actually. Tuples, lists, strings, even ranges.

first, second, third = "abc"
print(first, second, third)

Output

a b c

But usually, we use it with tuples and lists.

Swapping Variables in Python

Unpacking gives us a very elegant way to swap two variables.

Without unpacking, we need a temporary variable.

a = 5
b = 10
temp = a
a = b
b = temp
print(a, b)

Output

10 5

With unpacking, we can do it in one line.

a = 5
b = 10
a, b = b, a
print(a, b)

Output

10 5

That is much cleaner. And it is a common Python idiom.

Unpacking with the Star Operator in Python

Sometimes we do not know how many items there are. Or we only care about a few of them.

We can use the * operator to capture the rest into a list.

numbers = [1, 2, 3, 4, 5]
first, *rest = numbers
print(first)
print(rest)

Output

1
[2, 3, 4, 5]

The first gets the first item. The rest gets everything else as a list.

We can put the star anywhere.

first, *middle, last = numbers
print(first)
print(middle)
print(last)

Output

1
[2, 3, 4]
5

That is very handy.

We can also use it to ignore values.

first, *_, last = numbers
print(first)
print(last)

Output

1
5

The _ is just a variable name. By convention, it means β€œI do not care about this.” The star collects the middle values, but we do not use them.

Unpacking in Function Calls in Python

We can unpack a list or tuple when calling a function. Use * for positional arguments.

def add(a, b, c):
return a + b + c
numbers = [1, 2, 3]
print(add(*numbers))

Output

6

The *numbers unpacks the list into three separate arguments.

We can also unpack a dictionary with ** for keyword arguments.

def greet(name, greeting):
print(f"{greeting}, {name}!")
info = {"name": "Alex", "greeting": "Hello"}
greet(**info)

Output

Hello, Alex!

This is very useful when we have data in a collection and we want to pass it to a function.

Nested Unpacking in Python

We can unpack nested structures too.

person = ("Alex", (25, "London"))
name, (age, city) = person
print(name)
print(age)
print(city)

Output

Alex
25
London

The inner tuple (25, "London") is unpacked into age and city. That is a clean way to handle nested data.

Python Packing and Unpacking: A Real-Life Example

Let’s say we have a list of coordinates.

points = [(1, 2), (3, 4), (5, 6)]
for x, y in points:
print(f"x = {x}, y = {y}")

Output

x = 1, y = 2
x = 3, y = 4
x = 5, y = 6

That is a common pattern. We loop through a list of tuples. And we unpack each tuple into variables right in the loop.

Another Example β€” Returning Multiple Values

Functions can return multiple values as a tuple. And we can unpack them.

def get_min_max(numbers):
return min(numbers), max(numbers)
numbers = [4, 2, 9, 1, 7]
minimum, maximum = get_min_max(numbers)
print(f"Min: {minimum}, Max: {maximum}")

Output

Min: 1, Max: 9

That is very clean.

Common Mistakes with Python Packing and Unpacking

Mistake 1: Mismatched Number of Variables

point = (10, 20, 30)
x, y = point # Error!

So what do we do? We match the number of variables to the number of items. Or we use * to capture the rest.

Mistake 2: Forgetting the Star When We Need It

numbers = [1, 2, 3, 4]
first, second = numbers # Error!

So what do we do? We use the star.

first, *rest = numbers

Mistake 3: Using the Same Variable Name Twice

a, a = (1, 2)
print(a) # 2

This is allowed but confusing. Let’s not do it.

Mistake 4: Unpacking a String and Expecting Words

sentence = "Hello world"
a, b = sentence # Error! Too many characters

Strings unpack into characters, not words. We use split() first if we want words.

a, b = sentence.split()

Next, we will learn about Python Tuples vs Lists and choose the right collection for each situation.