Home >Backend Development >Python Tutorial >How Do * and Operators Unpack Arguments in Python Function Calls?
Unpacking in Function Calls Using and Operators*
Python's and * operators play crucial roles in function calls, allowing for convenient unpacking of sequences, collections, and dictionaries.
Unpacking Sequences and Collections with * (Single Star)
The * (single star) operator unpacks a sequence or collection into positional arguments. For example, consider the following code:
def add(a, b): return a + b values = (1, 2) s = add(*values) # unpacks values into individual arguments
This is equivalent to writing:
s = add(1, 2)
Unpacking Dictionaries with (Double Star)**
The ** (double star) operator performs a similar operation for dictionaries, extracting named arguments. For instance, given:
values = {'a': 1, 'b': 2} s = add(**values) # unpacks values as keyword arguments
This is equivalent to:
s = add(a=1, b=2)
Combining Operators for Function Call Unpacking
Both and * operators can be used together in a function call. For instance, given:
def sum(a, b, c, d): return a + b + c + d values1 = (1, 2) values2 = {'c': 10, 'd': 15} s = add(*values1, **values2) # combines sequence and dictionary unpacking
This is equivalent to:
s = sum(1, 2, c=10, d=15)
Performance Implications
Unpacking operations with and * incur some overhead due to tuple and dictionary creation. However, for small data sets, the performance impact is generally negligible. For larger data sets, consider alternative methods for efficiency, such as using tuple and dictionary comprehension.
Additional Uses in Function Parameters
The above is the detailed content of How Do * and Operators Unpack Arguments in Python Function Calls?. For more information, please follow other related articles on the PHP Chinese website!