As mentioned in PythonCookbook, *
can be added before a tuple, and what does *
mean here?
Chapter 1.18. Mapping Names to Sequence Elements:
from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price'])
s = Stock(*rec)
# here rec is an ordinary tuple, for example: rec = ('ACME', 100, 123.45)
In the same section, **dict
presents:
from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price', 'date', 'time'])
# Create a prototype instance
stock_prototype = Stock('', 0, 0.0, None, None)
# Function to convert a dictionary to a Stock
def dict_to_stock(s):
return stock_prototype._replace(**s)
What is **
's function here?
In a function call
*t
means "treat the elements of this tuple as positional arguments to this function call."Since v3.5, you can also do this in a list/tuple/set literals:
**d
means "treat the key-value pairs in the dictionary as additional named arguments to this function call."Since v3.5, you can also do this in a dictionary literals:
In a function signature
*t
means "take all additional positional arguments to this function and pack them into this parameter as a tuple."**d
means "take all additional named arguments to this function and insert them into this parameter as dictionary entries."In assignments and
for
loops*x
means "consume additional elements in the right hand side", but it doesn't have to be the last item. Note thatx
will always be a list: