Functions
Multiple Return Values
Python multiple return values are tuple return values with friendly syntax. return a, b creates one tuple containing two positions.
Most callers unpack that tuple immediately. Good target names make the meaning of each returned position explicit.
Use this for small, fixed groups of results. For larger records, a dataclass or named tuple usually communicates better.
Returning values separated by commas returns one tuple. The tuple is visible if the caller stores the result directly.
Source
def divide_with_remainder(total, size):
quotient = total // size
remainder = total % size
return quotient, remainder
result = divide_with_remainder(17, 5)
print(result)Output
(3, 2)Callers usually unpack the tuple immediately or soon after. The names at the call site document what each position means.
Source
boxes, leftover = result
print(boxes)
print(leftover)Output
3
2Notes
- A comma creates a tuple;
return a, breturns one tuple containing two values. - Unpacking at the call site gives each returned position a meaningful name.
- Use a class-like record when the result has many fields.
See also
Run the complete example
Expected output
(3, 2)
3
2
Execution time appears here after you run the example.