-1

Code:

def func(a=[]):
    a.append(1)
    print(a)

func()
func()
func()

Output:

[1]
[1, 1]
[1, 1, 1]

I thought the default value, the list, would be re-assigned every time func was called, and the answer would be:

[1]
[1]
[1]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

1

You say you "thought the default value, the list, would be re-assigned everytime func be called." You thought wrong. If you are learning Python you should work through the official tutorial at some point. Here is what it says about default arguments:

The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.

Read the tutorial for details.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50