Unveiling the Significance of (Double Star) and (Star) in Function Parameters*
In Python, function parameters denoted by args and *kwargs serve as versatile mechanisms to accommodate arbitrary arguments.
Unpacking Positional Arguments with *args
The *args parameter gathers all positional arguments that surpass the predefined ones into a tuple. For instance:
def foo(*args): for arg in args: print(arg)
This function can accept an arbitrary number of positional arguments, such as:
foo(1) # Output: 1 foo(1, 2, 3) # Output: 1 2 3
Assembling Keyword Arguments with kwargs**
On the other hand, **kwargs collects all keyword arguments into a dictionary.
def bar(**kwargs): for key, value in kwargs.items(): print(key, value)
Calling this function with keyword arguments yields:
bar(name='John', age=30) # Output: name John, age 30
Interplay of args and kwargs*
Both idioms can be combined to allow a mix of fixed and variable arguments:
def foo(kind, *args, bar=None, **kwargs): print(kind, args, bar, kwargs)
This function can be called as follows:
foo(123, 'a', 'b', apple='red') # Output: 123 ('a', 'b') None {'apple': 'red'}
Additional Use Cases
def foo(bar, lee): print(bar, lee) baz = [1, 2] foo(*baz) # Output: 1 2
first, *rest = [1, 2, 3, 4] # first = 1 # rest = [2, 3, 4]
def func(arg1, arg2, arg3, *, kwarg1, kwarg2): pass
This function requires three positional arguments and any number of keyword arguments after *.
The above is the detailed content of What's the Difference Between `*args` and `kwargs` in Python Function Parameters?. For more information, please follow other related articles on the PHP Chinese website!