Home >Backend Development >Python Tutorial >How Do Single and Double Star Operators (*) and () Handle Variable Arguments in Python Function Definitions?

How Do Single and Double Star Operators (*) and () Handle Variable Arguments in Python Function Definitions?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 16:57:10783browse

How Do Single and Double Star Operators (*) and () Handle Variable Arguments in Python Function Definitions?

Parameter Unpacking: and in Function Definitions*

Function definitions in Python can leverage the (star) and * (double star) operators to handle varied numbers of arguments.

Single Star Operator (*)

The operator (also known as "var-args" or "splat") collects all positional arguments passed to the function into a tuple called args. For instance, in the definition below:

def foo(x, y, *args):
    pass

If args is invoked with foo(1, 2, 3, 4, 5), the args tuple will contain (3, 4, 5).

Double Star Operator ()**

The operator (also known as "var-kwargs" or "keyword splat") captures all keyword arguments as a dictionary named kwargs**. In the following definition:

def bar(x, y, **kwargs):
    pass

When bar is invoked with bar(1, 2, name='Alice', age=30), the kwargs dictionary will contain {'name': 'Alice', 'age': 30}.

Mixing Standard and Variable Arguments

Function definitions can combine normal arguments with variable arguments using *:

def foo(kind, *args, bar=None, **kwargs):
    pass

When invoked with foo(123, 'a', 'b', apple='red'), the variables 'kind', 'args', 'bar', and 'kwargs' will contain:

  • kind = 123
  • args = ('a', 'b')
  • bar = None
  • kwargs = {'apple': 'red'}

Unpacking Argument Lists

*: can also be used to unpack argument lists when calling functions:

def foo(bar, lee):
    pass

baz = [1, 2]

foo(*baz) # Unpacks baz into [1, 2] for bar and lee

Extended Iterable Unpacking (Python 3)

In Python 3, *l can be used on the left side of an assignment to unpack iterables into multiple variables:

first, *rest = [1, 2, 3, 4] # first = 1, rest = [2, 3, 4]

Keyword-Only Arguments (Python 3)

Python 3 introduces keyword-only arguments, where after *: only keyword arguments are allowed:

def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
    pass

The above is the detailed content of How Do Single and Double Star Operators (*) and () Handle Variable Arguments in Python Function Definitions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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