Return two values from a Python function and unpack them at the call site.
Python has no syntax for returning several values. A return statement takes one expression, so if you want to hand back more than one value then you return a tuple. The parentheses are usually left off, because a comma on its own already creates a tuple.
def min_and_max(values):
if not values:
return None, None
return min(values), max(values)
smallest, largest = min_and_max([4, 9, 2, 7])
print(smallest, largest) # 2 9
# The tuple is a normal object, so you can index it or keep it.
result = min_and_max([4, 9, 2, 7])
print(result) # (2, 9)
print(result[0], type(result).__name__)
# Unpacking needs a real sequence.
try:
value, = 42
except TypeError as err:
print('TypeError:', err)The comma in the return statement builds a tuple, and the unpacking on the left of the assignment splits that tuple back apart. It works because a tuple has a fixed length that Python knows about, so Python can unpack it directly instead of building a temporary list first.
There are two things to watch here. If the two sides have different lengths, the unpacking raises a ValueError that tells you how many values were expected. That is a useful failure, but it also means that a function whose return shape changes from call to call is a design smell. The single-value case is worth understanding too, because unpacking with a trailing comma requires a real sequence. Trying to unpack the integer 42 raises a TypeError, while unpacking a string would split it into its individual characters. So a function that sometimes returns a string and sometimes returns a tuple is asking for trouble.
If you need to return a variable number of values, then return a list or a tuple and unpack it with a star, as in head, *rest = result.