-2
>>> def foo(bar=[]):        
...    bar.append("apple")    
...    return bar

>>> foo()
["apple"]
>>> foo()
["apple", "apple"]
>>> foo()
["apple", "apple", "apple"]

Why did it add in "apple" instead of making a new list?

Rlz
  • 1,649
  • 2
  • 13
  • 36

1 Answers1

0

The answer is that the value for a function argument is only evaluated once when it is defined. Therefore, the argument is initialized to its default only when foo() is first defined. Then it calls to foo() and it will continue to use the same list to which bar was originally initialized.

A workaround for this is as follows:

>>> def foo(bar=None):
...    if bar is None:      # or if not bar:
...        bar = []
...    bar.append("baz")
...    return bar
...
>>> foo()
["baz"]
>>> foo()
["baz"]
>>> foo()
["baz"]

Credit goes to www.toptal.com

Rlz
  • 1,649
  • 2
  • 13
  • 36