argument-unpacking

How to extract parameters from a list and pass them to a function call [duplicate]

元气小坏坏 提交于 2019-11-26 10:58:13
问题 This question already has an answer here: Use of *args and **kwargs [duplicate] 11 answers What is a good, brief way to extract items from a list and pass them as parameters to a function call, such as in the example below? Example: def add(a,b,c,d,e): print(a,b,c,d,e) x=(1,2,3,4,5) add(magic_function(x)) 回答1: You can unpack a tuple or a list into positional arguments using a star. def add(a, b, c): print(a, b, c) x = (1, 2, 3) add(*x) Similarly, you can use double star to unpack a dict into

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

若如初见. 提交于 2019-11-26 01:17:19
问题 In the following method definitions, what does the * and ** do for param2 ? def foo(param1, *param2): def bar(param1, **param2): 回答1: The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation. The *args will give you all function parameters as a tuple: In [1]: def foo(*args): ...: for a in args: ...: print a ...: ...: In [2]: foo(1) 1 In [4]: foo(1,2,3) 1 2 3 The **kwargs will

Unpacking, extended unpacking, and nested extended unpacking

北慕城南 提交于 2019-11-25 23:51:11
问题 Consider these expressions... Please be patient... this is a LONG list... (Note: some expressions are repeated -- this is just to present a \"context\") a, b = 1, 2 # simple sequence assignment a, b = [\'green\', \'blue\'] # list asqignment a, b = \'XY\' # string assignment a, b = range(1,5,2) # any iterable will do # nested sequence assignment (a,b), c = \"XY\", \"Z\" # a = \'X\', b = \'Y\', c = \'Z\' (a,b), c = \"XYZ\" # ERROR -- too many values to unpack (a,b), c = \"XY\" # ERROR -- need

What does the star operator mean, in a function call? [duplicate]

こ雲淡風輕ζ 提交于 2019-11-25 21:48:15
问题 This question already has answers here : What does ** (double star/asterisk) and * (star/asterisk) do for parameters? (19 answers) asterisk in function call (3 answers) Closed last year . What does the * operator mean in Python, such as in code like zip(*x) or f(**k) ? How is it handled internally in the interpreter? Does it affect performance at all? Is it fast or slow? When is it useful and when is it not? Should it be used in a function declaration or in a call? 回答1: The single star *