A tuple is like a list that cannot change: point = (3, 4). The parentheses are optional in most places, which is why return lo, hi returns a tuple. Unpacking assigns the parts to names in one line: x, y = point, and a, b = b, a swaps two variables without a temporary.
Functions that need to hand back two things return a tuple and the caller unpacks it. Tuples also work as dictionary keys and in sets because they are immutable.
def divide(a, b):
return a // b, a % b
q, r = divide(17, 5)
print(q, r) # 3 2Your task
Write min_max(nums) returning the smallest and largest value as a tuple, split_name(full) returning the first and last word of a two-word name as a tuple, and, at the bottom, swap the values of a and b with tuple unpacking.
Hint 1
return min(nums), max(nums)
Hint 2
first, last = full.split(); return first, last. Swap with a, b = b, a.
Show the solution
def min_max(nums):
return min(nums), max(nums)
def split_name(full):
first, last = full.split()
return first, last
a = 1
b = 2
a, b = b, a