Tuple Unpacking

Multiple assignment with tuples

Interview Relevant: Pythonic feature

Tuple Unpacking

Assign multiple values at once.

Code Examples

Tuple unpacking techniques.

python
1# Basic unpacking
2x, y, z = (1, 2, 3)
3
4# Works with lists too
5a, b, c = [1, 2, 3]
6
7# Swap values
8a, b = b, a
9
10# Extended unpacking (Python 3)
11first, *rest = [1, 2, 3, 4]  # first=1, rest=[2,3,4]
12first, *middle, last = [1, 2, 3, 4]  # first=1, middle=[2,3], last=4
13
14# Ignore values
15x, _, z = (1, 2, 3)  # Ignore middle
16
17# Unpack in function calls
18def add(a, b, c):
19    return a + b + c
20args = (1, 2, 3)
21add(*args)  # Unpack tuple as arguments
22
23# Return multiple values (actually tuple)
24def min_max(lst):
25    return min(lst), max(lst)
26lo, hi = min_max([3, 1, 4])

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In