Tuples without parentheses
It's the commas that make a tuple, not the parentheses. Values separated by commas are a tuple even without them:
>>> numbers = 1, 2, 3
>>> numbers
(1, 2, 3)
>>> single = 5,
>>> single
(5,)A tuple of one value needs its comma too: (5) is just the number 5 in parentheses.
Returning several values
A function returns one value, but that value can be a tuple. So a function can give back several values by returning them separated by commas:
def to_minutes(total_seconds: int) -> tuple:
return total_seconds // 60, total_seconds % 60
result = to_minutes(135)
print(result)
minutes, seconds = to_minutes(135)
print(f"{minutes} min {seconds} s")
(2, 15)
2 min 15 sUnpacking
minutes, seconds = to_minutes(135) is called unpacking: the values of the tuple on the right go into the variables on the left, in order. The number of variables has to match the number of values:
point = (3, 7, 1)
x, y = point
Traceback (most recent call last):
File "main.py", line 2, in <module>
x, y = point
^^^^
ValueError: too many values to unpack (expected 2, got 3)Unpacking works in a for loop too. A loop over a list of tuples can unpack each one right away. That's what happens in for key, value in d.items(): items() gives each pair of the dictionary as a tuple.
pioneers = [("Ada", 1815), ("Alan", 1912), ("Grace", 1906)]
for name, year in pioneers:
print(name, year)
ages = {"Ada": 36, "Max": 41}
print(list(ages.items()))
Ada 1815
Alan 1912
Grace 1906
[('Ada', 36), ('Max', 41)]Swapping two values
To swap the values of two variables, you would normally need a helper variable, because the first assignment overwrites one of the values:
helper = a
a = b
b = helper
With a tuple it takes one line. Python first makes a tuple of the values on the right, and only then unpacks it into the variables on the left:
a = 1
b = 2
a, b = b, a
print(a, b)
2 1