Default Values ​​for a List of Variable Arguments in Python

Is it possible to set a default value for a list of variable arguments in Python 3?

Sort of:

def do_it(*args=(2, 5, 21)):
     pass

Interestingly, the list of variable arguments is of type tuple, but there is no tuple here.

+3
source share
2 answers

If not syntactically, then depending on what behavior you want:

def do_it(*args):
    if not args: args = (2, 5, 21)

or

def do_it(a=2, b=5, c=21, *args):
    args = (a,b,c)+args

must do it.

+4
source

Initializing such a list is usually not a good idea.

. , , , . ,

def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
rint f(3)

[1]
[1, 2]
[1, 2, 3]

, - , , .

+1

Source: https://habr.com/ru/post/1743845/


All Articles