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

后端 未结 5 2062
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 06:35

What does the * operator mean in Python, such as in code like zip(*x) or f(**k)?

  1. How is it handled internally in the int
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 07:21

    In a function call the single star turns a list into seperate arguments (e.g. zip(*x) is the same as zip(x1,x2,x3) if x=[x1,x2,x3]) and the double star turns a dictionary into seperate keyword arguments (e.g. f(**k) is the same as f(x=my_x, y=my_y) if k = {'x':my_x, 'y':my_y}.

    In a function definition it's the other way around: the single star turns an arbitrary number of arguments into a list, and the double start turns an arbitrary number of keyword arguments into a dictionary. E.g. def foo(*x) means "foo takes an arbitrary number of arguments and they will be accessible through the list x (i.e. if the user calls foo(1,2,3), x will be [1,2,3])" and def bar(**k) means "bar takes an arbitrary number of keyword arguments and they will be accessible through the dictionary k (i.e. if the user calls bar(x=42, y=23), k will be {'x': 42, 'y': 23})".

提交回复
热议问题