What does * tuple and ** dict mean in Python?

As mentioned in PythonCookbook, * can be added before a tuple, but what does * mean here?

Chapter 1.18. Display names in 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 is presented:

 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 the function ** here?

+6
source share
1 answer

In function call

*tuple means "treat the elements of this tuple as positional arguments for this function call."

 def foo(x, y): print(x, y) >>> t = (1, 2) >>> foo(*t) 1 2 

Since v3.5, you can also do this in a list / set / set of literals:

 >>> [1, *(2, 3), 4] [1, 2, 3, 4] 

**dict means "treat key-value pairs in the dictionary as additional named arguments for this function call."

 def foo(x, y): print(x, y) >>> d = {'x':1, 'y':2} >>> foo(**d) 1 2 

Since v3.5, you can also do this in dictionary literals:

 >>> d = {'a': 1} >>> {'b': 2, **d} {'b': 2, 'a': 1} 

In function signature

*tuple means "accept all additional positional arguments of this function and pack them into this parameter as a tuple."

 def foo(*x): print(x) >>> foo(1, 2) (1, 2) 

**dict means "accept all additional named arguments to this function and insert them into this parameter as entries in the dictionary".

 def foo(**d): print(d) >>> foo(x=1, y=2) {'y': 2, 'x': 1} 

In assignments and for loops

*x means "consume additional elements on the right side", but this does not have to be the last element. Note that x will always be a list:

 >>> x, *xs = (1, 2, 3, 4) >>> x 1 >>> xs [2, 3, 4] >>> *xs, x = (1, 2, 3, 4) >>> xs [1, 2, 3] >>> x 4 >>> x, *xs, y = (1, 2, 3, 4) >>> x 1 >>> xs [2, 3] >>> y 4 >>> for (x, *y, z) in [ (1, 2, 3, 4) ]: print(x, y, z) ... 1 [2, 3] 4 
+9
source

All Articles