Skip to content

Python unpack operator *

  • by

In Python, the unpacking operator * is used in various contexts to handle iterables (such as lists, tuples, and strings) in a flexible way. It allows you to extract elements from an iterable and distribute them as separate values. The * operator has different uses depending on where it is used.

Here’s a breakdown of the syntax for using the unpacking operator * in various contexts:

Function Arguments:

def my_function(arg1, arg2, *args):
    # Function body
    
values = [1, 2, 3, 4, 5]
my_function(*values)

Assignment:

first, *middle, last = [1, 2, 3, 4, 5]

Iterables:

concatenated = [*list1, *list2]

Extended Iterable Unpacking (Python 3.5+):

first, *rest = [1, 2, 3, 4, 5]
*beginning, last = [1, 2, 3, 4, 5]

The * operator is a powerful tool for working with iterables and makes your code more concise and flexible. Keep in mind that its behavior may slightly vary depending on the context in which it’s used.

Python unpack operator * example

Here are some practical examples of how the unpacking operator * can be used in different scenarios:

1. Unpacking in Function Arguments:

def print_values(arg1, arg2, *args):
    print("arg1:", arg1)
    print("arg2:", arg2)
    print("additional arguments:", args)

values = [1, 2, 3, 4, 5]
print_values(*values)

Output:

Python unpack operator

2. Unpacking in Assignment:

first, *middle, last = [1, 2, 3, 4, 5]
print("First:", first)
print("Middle:", middle)
print("Last:", last)

3. Unpacking in Iterables:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated = [*list1, *list2]
print("Concatenated list:", concatenated)

4. Extended Iterable Unpacking (Python 3.5+):

first, *rest = [1, 2, 3, 4, 5]
print("First:", first)
print("Rest:", rest)

*beginning, last = [1, 2, 3, 4, 5]
print("Beginning:", beginning)
print("Last:", last)

5. Unpacking in Tuple Creation:

values = [1, 2, 3, 4, 5]
tuple_with_unpacking = (*values,)
print("Tuple with unpacking:", tuple_with_unpacking)

6. Combining Lists with Unpacking:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = [*list1, 3.5, *list2, 7, 8, 9]
print("Combined list:", combined_list)

7. Unpacking and Repacking Dictionary Items:

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
combined_dict = {**dict1, **dict2, 'e': 5}
print("Combined dictionary:", combined_dict)

These examples showcase how the unpacking operator * can be used in various situations to manipulate and work with data in Python. The operator is versatile and can greatly simplify your code when dealing with collections of data.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading