Sub topic 11
Returning Multiple Values and Unpacking Arguments
This chapter assumes you can define and call functions, know how tuple packing and basic unpacking work, and have seen starred targets such as first, *rest = items. Here you will use both ideas at function boundaries: on the way out through return, and on the way in through * in a call.
Returning several values is returning one tuple
Python functions return exactly one object. When you write return a, b, the comma packs the values into a tuple, as in any other expression.
def min_max(values):
return min(values), max(values)
result = min_max([3, 1, 4, 1, 5])
print(result)
print(type(result))
lo, hi = min_max([3, 1, 4, 1, 5])
print(lo, hi)The first two prints show (1, 5) and <class 'tuple'>. The caller can keep the tuple whole or unpack it into names, as the last two lines do. The function does not know which one the caller will choose.
Unpacking arguments with `*`
The reverse direction also works. Putting * before an iterable in a call spreads its items into separate positional arguments.
args = (2, 10)
print(pow(*args))
print(pow(2, 10))Both lines print 1024. This matters when the arguments are built at runtime, for example read from a file or produced by another function. Because a returned tuple can be spread, you can chain two functions directly:
def min_max(values):
return min(values), max(values)
print(pow(*min_max([2, 3, 10])))min_max returns (2, 10), and pow(*...) receives 2 and 10, so the output is 1024.
More forms of `*` in calls
A call can contain several starred arguments, mixed with ordinary ones. Any iterable works, not just tuples.
print(*[1, 2, 3], sep="-")
print(*"ab", *range(2), sep=",")The output is 1-2-3 and then a,b,0,1.
A common idiom is zip(*pairs), which transposes a list of pairs into separate columns:
pairs = [(1, "a"), (2, "b"), (3, "c")]
numbers, letters = zip(*pairs)
print(numbers)
print(letters)This prints (1, 2, 3) and ('a', 'b', 'c'). The call is zip((1, "a"), (2, "b"), (3, "c")), and zip groups the first items together, then the second items.
Keyword arguments have a matching form. ** before a dictionary spreads its keys as parameter names:
def area(width, height):
return width * height
size = {"width": 3, "height": 4}
print(area(**size))This prints 12. The dictionary keys must match the parameter names exactly.
When to return a plain tuple
Returning a tuple suits small results whose order is obvious, such as (low, high) or (x, y). Once a result has more than three or four fields, callers must remember positions, and a mistake like swapping two values goes unnoticed. In that case return a named tuple, which still unpacks like a tuple but also offers result.low. A dictionary or a class fits better when fields are optional or may grow.
Common errors
f(*5)raisesTypeError, because*needs an iterable. Usef(*(5,))or justf(5).- Spreading a string spreads its characters, so
print(*"abc")passes three arguments. - Spreading a very large iterable builds all its arguments at once. Prefer passing the iterable itself when the function accepts one.
- A starred call argument must come before any
**mapping argument.
Exercise
Write a function split_name(full) that takes a string like "Ada Lovelace King" and returns the first word and the last word as two values. Then call it and unpack the result into first and last. What does it print for that string, and which tuple length does the function return?
Show answer
def splitname(full): words = full.split() return words[0], words[-1] first, last = splitname("Ada Lovelace King") print(first, last) It prints "Ada King". The function returns a tuple of length 2, so unpacking into two names works. A starred form would also work: first, *_, last = "Ada Lovelace King".split()