How does the asterisk (*) work in Python function definitions?

Patricia Arquette
Release: 2024-11-09 12:47:02
Original
357 people have browsed it

How does the asterisk (*) work in Python function definitions?

Understanding the Asterisk (*) in Python Function Definitions

In Python, the asterisk (*) holds significant meaning in defining functions. The reference documentation for function definitions sheds light on its usage:

  • Excess Positional Arguments: The syntax form *identifier accepts any remaining positional parameters not included in the function's signature and initializes them to a tuple. By default, an empty tuple is assigned if there are no excess positional arguments.
  • Excess Keyword Arguments: The syntax form **identifier stores any additional keyword arguments not accounted for in the function's signature and assigns them to a new dictionary. The default is an empty dictionary if there are no excess keyword arguments.

Here are tangible examples to illustrate their application:

Example 1: Excess Keyword Arguments

def foo(a, b, c, **args):
    print(f"a = {a}")
    print(f"b = {b}")
    print(f"c = {c}")
    print(args)

foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")
Copy after login

Example 2: Excess Positional Arguments

def foo(a, b, c, *args):
    print(f"a = {a}")
    print(f"b = {b}")
    print(f"c = {c}")
    print(args)

foo("testa", "testb", "testc", "excess", "another_excess")
Copy after login

Unpacking Arguments

The asterisk can also be used to unpack dictionaries or tuples into function arguments:

Example 3: Unpacking a Dictionary

def foo(a, b, c, **args):
    print(f"a={a}")
    print(f"b={b}")
    print(f"c={c}")
    print(f"args={args}")

argdict = {"a": "testa", "b": "testb", "c": "testc", "excessarg": "string"}
foo(**argdict)
Copy after login

Example 4: Unpacking a Tuple

def foo(a, b, c, *args):
    print(f"a={a}")
    print(f"b={b}")
    print(f"c={c}")
    print(f"args={args}")

argtuple = ("testa", "testb", "testc", "excess")
foo(*argtuple)
Copy after login

By understanding the asterisk's usage in Python function definitions, you can effectively handle excess arguments and unpack data into function arguments.

The above is the detailed content of How does the asterisk (*) work in Python function definitions?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template