Python: Packing and Unpacking Operator (*, **)

created:

updated:

tags: python

Single star *

Unpacking

We can use * to unpack arguments in a list or tuple.

Example:

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

def add_numbers(n1, n2, n3, n4, n5):
    return n1 + n2 + n3 + n4 + n5

In order to run add_numbers() with the elements in nums list, we can pass each argument such as add_numbers(nums[0], nums[1], nums[2], nums[3], nums[4]). However, there is an easier way to do this by using * operator.

Using *

We can call the same function as add_numbers(*nums).

When using * in this case, the number of arguments for the function must be the same as the length of the list we unpack.

Another example with using Python’s built-in function range().

range(3, 6)  # Calling `range()` with 3 and 6 as arguments
args = [3, 6]

# If we have `args` list, we can call `range()` as following:
range(*args)

Packing

We can use * to pack arguments in functions especially when we don’t know how many arguments may be passed.

def add_nums1(n1, n2, n3):
    print(n1, n2, ,n3)

# Similar function, but this time with packing arguments
def add_nums2(*nums):
    # Arguments passed come as a tuple. We can convert args tuple to a list
    # nums_list = list(*nums)
    print(nums)  # prints (1, 2, 3)
    print(*nums)  # prints 1, 2, 3

Double stars **

Unpacking

The double stars ** can be used to unpack items in a dictionary.

References