"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Do Single and Double Asterisks (*) Unpack Arguments in Python Functions?

How Do Single and Double Asterisks (*) Unpack Arguments in Python Functions?

Posted on 2025-02-26
Browse:498

How Do Single and Double Asterisks (*) Unpack Arguments in Python Functions?

Unpacking Arguments in Python with and (Double Star/Asterisk)*

In Python, the and * operators play crucial roles in unpacking arguments when calling functions.

Single Star *:
The single star (*) unpacks a sequence or collection into positional arguments. For example, consider the function:

def add(a, b):
    return a   b

The code below uses * to unpack the tuple values:

values = (1, 2)
s = add(*values)

This is equivalent to writing:

s = add(1, 2)

Double Star **:
The double star (**) performs a similar operation for dictionaries, providing values for named arguments. Consider the function:

def sum(a, b, c, d):
    return a   b   c   d

Unpacking the dictionary values2 using ** yields the following:

values2 = { 'c': 10, 'd': 15 }
s = add(**values2)

This is equivalent to:

s = sum(a=1, b=2, c=10, d=15)

Combination of and :*
Both and * can be used simultaneously in the same function call. For instance:

values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
s = add(*values1, **values2)

This is equivalent to:

s = sum(1, 2, c=10, d=15)

Parameter Unpacking:
In addition to unpacking arguments, and * can also be used for parameter unpacking in function definitions.

  • A parameter marked with * receives any number of positional arguments as a tuple.
  • A parameter marked with ** receives all keyword arguments as a dictionary.

For example:

def add(*values):
    # ...

def get_a(**values):
    # ...

Performance Implications:
The performance implications of using and * are generally minimal. The unpacking operation involves minimal overhead and does not affect the efficiency of the function itself. However, excessive unpacking can make code less readable and maintainable.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3