Python Packing and Unpacking

In the last lesson you learned Tuple Operations. So you can already slice a tuple, loop over it, and count what is inside. Now we look at a small trick Python does with tuples. You will use it almost every day, often without even noticing it. It is called packing and unpacking.

πŸ€” Why Packing and Unpacking?

Say you have a point on a screen. It has an x value and a y value. You could keep them in two separate variables and carry them around one by one. But they really belong together. They are one thing: a point.

The pain shows up in a few places. You want to return more than one value from a function. Or you want to swap two variables. Or you want to split a row of data into named pieces. Without a clean way to do this, you end up writing extra lines. You also need a temporary variable you did not really want.

Packing and unpacking fix that. Packing bundles several values into one tuple. Unpacking pulls them back out into separate variables in a single clean line.

πŸ“¦ Packing: many values into one tuple

When you write a few values separated by commas, Python quietly puts them together into one tuple. You do not even need the round brackets.

Here we put an x and a y value into a single variable called point.

point = 3, 4
print(point)
print(type(point))

Output

(3, 4)
<class 'tuple'>

See what happened? We gave Python two numbers with a comma between them. It packed them into the tuple (3, 4). The comma is what makes a tuple, not the brackets. The brackets are just there to make it easy to read.

Think of it like putting two things into one box. The box is the tuple. The comma is you closing the lid.

πŸ”“ Unpacking: one tuple back into many variables

Unpacking is the opposite move. You take a tuple and spread its values out into separate variables, one for each item.

Here we pull the x and y back out of point into two named variables.

point = 3, 4
x, y = point
print(x)
print(y)

Output

3
4

On the left of the = we wrote two variable names. On the right we had a tuple with two values. Python matched them up in order. The first value went into x. The second went into y. That is unpacking.

There is one rule to remember. The number of names on the left must match the number of values on the right.

If they do not match, Python stops and tells you.

point = 3, 4
x, y, z = point # only two values, but three names

Output

ValueError: not enough values to unpack (expected 3, got 2)

Note

Unpacking is not only for tuples. It works for lists and other ordered collections too. So a, b = [1, 2] works the same way. We focus on tuples here because that is the natural shape values come in.

πŸ” The clean variable swap

Here is the trick that makes people smile the first time they see it. Say Alex has two variables and wants to swap their values. In many languages you need a third temporary variable. It holds one value while you move the other.

This is the old way, with a spare variable just to hold a value for a moment.

a = 1
b = 2
# ❌ Avoid: extra temporary variable
temp = a
a = b
b = temp
print(a, b)

Output

2 1

Python lets you do the same thing in one line. This is packing and unpacking working together.

a = 1
b = 2
# βœ… Good: swap in one line
a, b = b, a
print(a, b)

Output

2 1

So how does this work? Look at the right side first. b, a gets packed into a tuple (2, 1). Then that tuple is unpacked into a, b on the left. Python builds the whole right side before it assigns anything. So there is no need for a temporary variable. The two values just trade places.

⭐ Grab the rest with a star

Sometimes you want the first value by itself. You do not care how many values come after it. You just want β€œthe rest” in one go. Put a * in front of a name. That name will collect everything left over into a list.

Here we pull off the first number and let one starred name catch all the others.

numbers = (10, 20, 30, 40, 50)
first, *others = numbers
print(first)
print(others)

Output

10
[20, 30, 40, 50]

first took the very first value, 10. The starred name others collected everything that was left into a list [20, 30, 40, 50]. Notice the starred part always comes out as a list. That is true even if it catches just one value or none at all.

The star does not have to be at the start. You can grab the first, the last, and let the star soak up the middle.

scores = (90, 75, 80, 85, 100)
first, *middle, last = scores
print(first)
print(middle)
print(last)

Output

90
[75, 80, 85]
100

Python fills in first and last because their positions are fixed. Then *middle takes whatever sits in between. Only one name in a line is allowed to have the star. Otherwise Python would not know where the middle starts and ends.

🎁 Returning several values from a function

This is where unpacking really earns its place. A function in Python returns one thing. But if you separate several values with commas, they get packed into one tuple. So it feels like the function hands back many values at once. The caller then unpacks them.

Here a function looks at a list of numbers and gives back both the smallest and the largest.

def min_and_max(values):
smallest = min(values)
largest = max(values)
return smallest, largest # packs into a tuple
low, high = min_and_max([4, 9, 1, 7, 3]) # unpacks the tuple
print(f"Lowest is {low}, highest is {high}")

Output

Lowest is 1, highest is 9

Read it from the inside out. return smallest, largest packs the two results into the tuple (1, 9). On the calling line, low, high = unpacks that tuple. So low becomes 1 and high becomes 9. No tuple ever needs a name. It is packed and unpacked in the same breath.

Here is a more real example. Imagine a row of user data and you want to read it into clear names.

user = ("Riya", 28, "riya@example.com")
name, age, email = user
print(f"{name} is {age} and can be reached at {email}")

Output

Riya is 28 and can be reached at riya@example.com

Reading name, age, email = user tells the whole story in one line. Anyone who reads your code later knows exactly what each piece of that row means. That is much friendlier than user[0], user[1], and user[2] scattered around.

⚠️ Common Mistakes

A few small things trip people up. None of them are hard once you have seen them.

  • Counts must match. If the left side has three names and the right side has two values, Python raises a ValueError. Either fix the count or use a star to absorb the extra.
  • Forgetting the comma when packing one value. single = 5 is just the number 5. To make a one-item tuple you need the comma: single = 5,.
  • Thinking the starred part is a tuple. It is not. A starred name like *others always gives you a list, even inside tuple unpacking.
  • Only one star per line. You cannot write a, *b, *c = values. Python cannot tell where one greedy name ends and the next begins.

Here is the count mistake and its fix side by side.

data = (1, 2, 3, 4)
# ❌ Avoid: three names for four values
a, b, c = data # ValueError
# βœ… Good: let a star catch the extras
a, b, *c = data # a=1, b=2, c=[3, 4]

βœ… Best Practices

Small habits that keep this clean and easy to read.

  • Unpack into names that say what the value means. x, y = point reads far better than a, b = point.
  • Use a, b = b, a for swaps. It is shorter and there is no spare variable to manage.
  • Reach for *rest when you truly care only about the first or last item and want the remainder together.
  • If you only need one value out of a tuple and want to ignore another, use an underscore as a throwaway name, like name, _ = person. It tells the reader you meant to skip that part.

🧩 What You’ve Learned

A quick recap of what you can now do.

  • βœ… Pack several values into one tuple just by separating them with commas.
  • βœ… Unpack a tuple back into separate, well-named variables in one line.
  • βœ… Swap two variables cleanly with a, b = b, a and no temporary variable.
  • βœ… Use a starred name like *rest to grab the leftover values as a list.
  • βœ… Return several values from a function and unpack them at the call.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What does `point = 3, 4` create?

    Why: Commas between values pack them into a tuple, so point becomes (3, 4); the brackets are optional.

  2. 2

    After `first, *others = (10, 20, 30, 40)`, what is `others`?

    Why: A starred name always collects the leftover values into a list, so others is [20, 30, 40].

  3. 3

    Why does `a, b = b, a` swap two variables without a temporary variable?

    Why: Python builds the whole right side (b, a) as a tuple before assigning, so the values trade places with no temp needed.

  4. 4

    What happens when a function ends with `return low, high`?

    Why: The comma packs low and high into a single tuple, which the caller unpacks with something like x, y = func().

πŸš€ What’s Next?

You now know how tuples bundle and unbundle values. So the natural next question is when to pick a tuple over a list in the first place. That is exactly what we look at next.

Tuple vs List

Share & Connect