Why does *args argument unpacking give a tuple?

前端 未结 3 1597
孤城傲影
孤城傲影 2021-01-06 10:03

In python, it is possible to define a function taking an arbitrary number of positional arguments like so:

def f(*args):
    print(args)
f(1, 2, 3)  # (1, 2,         


        
3条回答
  •  渐次进展
    2021-01-06 10:56

    Why not? The thing about tuple is, that you can not change it after creation. This allows to increase speed of executing your script, and you do not really need a list for your function arguments, because you do not really need to modify the given arguments of a function. Would you need append or remove methods for your arguments? At most cases it would be no. Do you want your program run faster. That would be yes. And that's the way the most people would prefer to have things. The *args thing returns tuple because of that, and if you really need a list, you can transform it with one line of code!

    args = list(args)
    

    So in general: It speeds up your program execution. You do not it to change the arguments. It is not that hard to change it's type.

提交回复
热议问题