Python / Core Python Fundamentals Interview Questions
What is tuple unpacking and extended unpacking in Python?
Unpacking assigns the individual elements of a sequence to multiple variables in a single statement. The left side must have the same number of names as the sequence has elements, or you get a ValueError.
# Basic unpacking x, y, z = (10, 20, 30) first, second = 'AB' # Swap without a temp variable a, b = 1, 2 a, b = b, a print(a, b) # 2 1 # Unpacking a function return value def min_max(nums): return min(nums), max(nums) lo, hi = min_max([5, 2, 8, 1]) print(lo, hi) # 1 8
Extended unpacking (Python 3+) uses the starred expression *rest to collect everything that does not fit into the explicit names:
first, *middle, last = [1, 2, 3, 4, 5] print(first) # 1 print(middle) # [2, 3, 4] print(last) # 5 # Useful for parsing structured payloads header, *records = open('data.csv').readlines() # Discard parts you don't need with _ _, important, _ = ('ignore', 'keep this', 'ignore')
Unpacking works on any iterable — lists, tuples, strings, generators, files. You can also unpack in a for loop: for x, y in [(1,2),(3,4)]:. Nested unpacking (a, (b, c)) = (1, (2, 3)) works but hurts readability; prefer flatter structures.
More Related questions...