Unpacking in Python

Python's unpacking allows you to assign values from sequences like lists, tuples, dictionaries, and more, into variables in a single, concise operation. It makes code cleaner, reduces boilerplate, and is especially useful when dealing with iterable objects.

1. Basic Unpacking (Tuples and Lists)

In Python, you can unpack values from a tuple or list into individual variables.

Example 1: Tuple unpacking

# Tuple with three values
coordinates = (1, 2, 3)
x, y, z = coordinates

print(x)  # Output: 1
print(y)  # Output: 2
print(z)  # Output: 3

Here, the values of the tuple coordinates are unpacked into the variables x, y, and z.

Example 2: List unpacking

# List with four values
numbers = [10, 20, 30, 40]
a, b, c, d = numbers

print(a)  # Output: 10
print(b)  # Output: 20
print(c)  # Output: 30
print(d)  # Output: 40

2. Unpacking with Wildcards (*)

You can use * to unpack multiple values into a list. This is useful when you don’t know the exact number of elements to unpack, or you want to capture a subset of elements.

Example 3: Using * for the rest of the values

numbers = [1, 2, 3, 4, 5]

a, *rest = numbers
print(a)      # Output: 1
print(rest)   # Output: [2, 3, 4, 5]

*start, end = numbers
print(start)  # Output: [1, 2, 3, 4]
print(end)    # Output: 5

In the example above, *rest collects all elements except the first, and *start collects all elements except the last.

3. Dictionary Unpacking

Dictionaries can also be unpacked, though it works differently from lists and tuples. The ** operator is used for unpacking dictionaries.

Example 4: Merging dictionaries using unpacking

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

# Merging two dictionaries
merged_dict = {**dict1, **dict2}
print(merged_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

You can also unpack a dictionary into function arguments using the ** syntax.

Example 5: Function argument unpacking

def func(x, y, z):
    print(x, y, z)

data = {'x': 10, 'y': 20, 'z': 30}
func(**data)  # Output: 10 20 30

4. Unpacking in Loops

Unpacking is frequently used when iterating over lists of tuples or other iterable data structures.

Example 6: Unpacking in a loop

pairs = [(1, 'one'), (2, 'two'), (3, 'three')]

for number, name in pairs:
    print(f"Number: {number}, Name: {name}")

# Output:
# Number: 1, Name: one
# Number: 2, Name: two
# Number: 3, Name: three

5. Unpacking Return Values

Many functions return tuples or other iterable objects. Unpacking allows you to easily retrieve individual return values.

Example 7: Unpacking function return values

def get_coordinates():
    return (1.0, 2.0)

x, y = get_coordinates()
print(x)  # Output: 1.0
print(y)  # Output: 2.0

6. Nested Unpacking

Python also supports unpacking nested structures like lists of lists or tuples of tuples.

Example 8: Nested unpacking

data = [(1, (2, 3)), (4, (5, 6))]

for a, (b, c) in data:
    print(f"a={a}, b={b}, c={c}")

# Output:
# a=1, b=2, c=3
# a=4, b=5, c=6

7. Unpacking with Ignored Values

You can ignore certain values during unpacking by using an underscore (_), which is commonly used to denote "throwaway" values.

Example 9: Ignoring values

data = (1, 2, 3, 4)

a, b, _, _ = data
print(a, b)  # Output: 1 2

8. Unpacking and Enumerate

Unpacking is often used with the enumerate() function to loop over both the index and the values of a list.

Example 10: Unpacking with enumerate

fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Fruit: {fruit}")

# Output:
# Index: 0, Fruit: apple
# Index: 1, Fruit: banana
# Index: 2, Fruit: cherry

Conclusion

Unpacking is a powerful feature in Python that simplifies code by allowing easy assignment of values from iterables into variables. It works with tuples, lists, dictionaries, and nested data structures, and it can be combined with wildcard operators like * for flexible unpacking.

Last updated

Was this helpful?