Unpacking Argument Lists of Defining Functions

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the * operator to unpack the arguments out of a list or tuple:

>>> list(range(3,6))
[3, 4, 5]
>>> args=[3, 6]
>>> list(range(*args))
[3, 4, 5]

In the same fashion, dictionaries can deliver keywood arguments with the ** operator:

>>> def parrot(voltage, state='a stiff', action='voom'):
... print("-- This parrot wouldn't", action, end=' ')
... print("if you put", voltage, "volts through it.", end=' ')
... print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,167评论 0 10
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,750评论 0 38
  • 函数调用 Built-in Functions abs(x) Return the absolute value ...
    叫我七夜阅读 4,924评论 0 0
  • 今天是周四,明天就周五了,这样算来,又坚持运动一个礼拜了。我记不得什么时候开始决定保持运动了,就从上个礼拜算起吧,...
    努力克服懒癌阅读 3,532评论 0 48
  • 白色桃花 红色桃花 三角梅 五月如歌,又添风韵 守 望 天 空 春风清拂盈盈的心事,流水静听心灵的声音,四月的天空...
    江离菲菲阅读 4,806评论 0 2

友情链接更多精彩内容