Tuple Unpacking

Tuple unpacking allows you to assign the values from a tuple to a group of variables in a single statement. With tuple unpacking, you can essentially unpack the values stored within the tuple and assign them to the variables directly.

Syntax of Tuple Unpacking

Here’s the basic syntax for tuple unpacking in Python:

1(a, b) = (1, 2)

In the above example, (1, 2) is a tuple and we’re unpacking its values into variables a and b. After this line executes, a will hold a value of 1 and b will hold a value of 2.

Using Tuple Unpacking

Let’s look at a more complex example to understand the concept better:

1student_tuple = ("John Doe", 12, "8th Grade")
2
3(name, roll_no, grade) = student_tuple
4print(name)
5print(roll_no)
6print(grade)

In this example, each variable on the left side of the equals sign (=) takes on the value of its corresponding item in the tuple. After executing these lines, name will be "John Doe", roll_no will be 12, and grade will be "8th Grade".

Note

Unpacking requires that the number of variables on the left side of the assignment operator (=) matches the number of values in the tuple. If the numbers don’t match, a ValueError is raised.

Swapping Values Using Tuple Unpacking

One practical use of tuple unpacking is swapping the values of two variables:

1x = 5
2y = 10
3
4x, y = y, x  # Swap the values
5print(x)
6print(y)

In this example, the values of x and y get swapped. After these lines execute, x will hold the value 10 and y will hold the value 5.

Tuple unpacking is a powerful feature in Python that allows you to assign multiple variables at once. It leads to cleaner, more readable code, especially when used in combination with other Python features like functions returning multiple values.

Remember, the Pythonic way is often the way that leads to the most readable and understandabale code, and tuple unpacking certainly fits that description.