What Is Tuple Packing and Unpacking in Python?
In Python, tuple packing and tuple unpacking are convenient ways to store multiple values in a tuple and extract them into variables.
-
Packing : combining values into a single tuple
-
Unpacking : extracting individual values from a tuple into variables
Tuples are lightweight and useful for grouping related data.
1. Tuple Packing
Tuple packing lets you place multiple values into a tuple automatically without parentheses.
data = 10, 20, 30, 40 print(data) # Output: # (10, 20, 30, 40)Here, all values are “packed” into a tuple named data.
Packing with Parentheses
You can also use parentheses explicitly
data = (1, 2, 3) print(data) # Output: # (1, 2, 3)2. Tuple Unpacking
Tuple unpacking lets you assign tuple values to variables in one statement.
person = ("Alice", 25, "Delhi") name, age, city = person print(name) print(age) print(city) # Output: # Alice # 25 # DelhiEach variable receives the corresponding value based on position.
3. Unpacking with Different Data Types
info = ("John", True, 3.14) name, status, value = info print(name) print(status) print(value) # Output: # John # True # 3.14Unpacking works regardless of the data type.
4. Using * for Extra Values
If the tuple has more values than variables, you can use * to gather the extra items.
nums = (1, 2, 3, 4, 5) a, b, *rest = nums print(a) print(b) print(rest) # Output: # 1 # 2 # [3, 4, 5]Here, rest collects the remaining items as a list.
5. Unpack into Existing Variables
You can overwrite existing variables using tuple unpacking.
x, y = (10, 20) print(x, y) # Output: # 10 20 This assigns values directly to x and y.
Key Points to Remember
-
Packing collects values into a tuple.
-
Unpacking assigns tuple values to variables.
-
Use
*to gather extra items. -
Works with any data type.