Home > Backend Development > Python Tutorial > How Do Single and Double Asterisks (*) Unpack Arguments in Python Functions?

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

DDD
Release: 2024-12-20 11:08:09
Original
669 people have browsed it

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
Copy after login

The code below uses * to unpack the tuple values:

values = (1, 2)
s = add(*values)
Copy after login

This is equivalent to writing:

s = add(1, 2)
Copy after login

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
Copy after login

Unpacking the dictionary values2 using ** yields the following:

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

This is equivalent to:

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

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)
Copy after login

This is equivalent to:

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

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):
    # ...
Copy after login

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.

The above is the detailed content of How Do Single and Double Asterisks (*) Unpack Arguments in Python Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template