0

How would you define a function that takes an optional argument and appends to it without having to provide the argument? The code is something like

def myfunc(value, values=[]):
    values.append(value)
    return values

print(myfunc("item"))
print(myfunc("item"))

expected output would be

['item']
['item']

instead of

['item']
['item', 'item']

1 Answers1

1

Avoid using mutable (dicts, lists etc) as default arguments.

Instead you can do the following.

def myfunc(value, values=None):
    if values is None:
        values = []
    values.append(value)
    return values

print(myfunc("item"))
print(myfunc("item"))
user
  • 5,370
  • 8
  • 47
  • 75