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:
另有一种相反的情况: 当你要传递的参数已经是一个列表但要调用的函数却接受分开一个个的参数值. 这时候你要把已有的列表拆开来. 例如内建函数 range() 要独立的 start, stop 参数. 你可以在调用函数时加一个 *
操作符来自动把参数列表拆开:
>>> range(3, 6) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> range(*args) # call with arguments unpacked from a list [3, 4, 5]