What does the asterisk do in Python other than multiplication and exponentiation? [duplicate]

北城余情 提交于 2019-12-01 06:25:02

Single asterisk in before a seqable object unpacks it, like Joran showed:

In [1]: def f(*args): return args

In [2]: f(1,2,3)
Out[2]: (1, 2, 3)

In [3]: f(*[1,2,3,4])
Out[3]: (1, 2, 3, 4)

(Note a third application for *: in function definition an asterisk indicates a variable length list of arguments, all are being packed into one list, args, in In [1])

Also worth noting is that a double asterisk (**) does a dictionary unpacking:

In [5]: def g(foo=None, bar=42): return foo,bar

In [6]: g()
Out[6]: (None, 42)

In [7]: g(*[1,2])
Out[7]: (1, 2)

In [8]: g(**{'foo': 'FOO', 'bar': 'BAR'})
Out[8]: ('FOO', 'BAR')
Joran Beasley

it unpacks the arguments

function(1,2,3)  ==  function(*[1,2,3])

it makes it easy to use variables to pass in to functions

args = [1,2,3]
func(*args) #much nicer than func(args[0],args[1],args[2],...)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!