0
0
Pythonprogramming~5 mins

Tuple unpacking in Python

Choose your learning style9 modes available
Introduction

Tuple unpacking helps you take values from a group and put them into separate boxes (variables) easily.

When you get multiple values from a function and want to save each value separately.
When you want to swap two values without using a temporary box.
When you want to quickly assign many values from a list or tuple to variables.
When you want to loop over pairs or groups of values and handle each part separately.
Syntax
Python
a, b = (1, 2)

You write variables on the left separated by commas, and a tuple or list on the right.

The number of variables must match the number of values in the tuple or list.

Examples
Assigns 10 to x and 20 to y from the tuple.
Python
x, y = (10, 20)
Unpacks a list into variables name and age.
Python
name, age = ['Alice', 30]
Swaps the values of a and b using tuple unpacking.
Python
a, b = b, a
Assigns 1 to first and the rest of the values to a list called rest.
Python
first, *rest = (1, 2, 3, 4)
Sample Program

This program gets a point as a tuple, unpacks it into x and y, prints them, then swaps their values and prints again.

Python
def get_point():
    return (4, 5)

x, y = get_point()
print(f"x = {x}")
print(f"y = {y}")

# Swap example
x, y = y, x
print(f"After swap: x = {x}, y = {y}")
OutputSuccess
Important Notes

If the number of variables and values don't match, Python will give an error.

You can use * to collect multiple values into a list during unpacking.

Summary

Tuple unpacking lets you assign multiple values to variables in one line.

It works with tuples, lists, and other iterable groups.

It makes code cleaner and easier to read when handling multiple values.