Unpack Tuples
Unpacking tuples in Python allows you to assign the elements of a tuple to multiple variables in a single line. This is often used in scenarios where a function returns multiple values as a tuple, and you want to assign those values to separate variables. Here's how tuple unpacking works:
Basic Tuple Unpacking:
coordinates = (3, 4)
x, y = coordinates
# Now, x is 3 and y is 4
In this example, the values (3, 4)
are unpacked into the variables x
and y
.
Unpacking with Functions:
def get_coordinates():
return 3, 4
x, y = get_coordinates()
# Now, x is 3 and y is 4
Functions can return multiple values as a tuple, and you can directly unpack those values into variables.
Ignoring Unneeded Values:
coordinates = (3, 4, 5)
x, y, _ = coordinates
# Now, x is 3, y is 4, and 5 is ignored
If you don't need all the values in the tuple, you can use an underscore (_
) to indicate that you want to ignore that particular value.
Extended Unpacking:
first, *rest = (1, 2, 3, 4, 5)
# Now, first is 1, and rest is [2, 3, 4, 5]
The *
operator can be used for extended unpacking, allowing you to assign the first element to one variable and the rest to another variable as a list.
Unpacking Nested Tuples:
coordinates = ((1, 2), (3, 4))
(x1, y1), (x2, y2) = coordinates
# Now, x1 is 1, y1 is 2, x2 is 3, and y2 is 4
You can also unpack nested tuples by matching the structure.
Tuple unpacking is a convenient and readable way to work with multiple values returned from functions or stored in tuples. It makes code concise and expressive, especially in scenarios where you are dealing with pairs or sets of related values.