1

Here are two pieces of codes which were under the standard of python3.6. And they are the examples in the docs of python3.6(tutorial, page25). The first is:

def f(a, L=[]):
    L.append(a)
    return L
print(f(1))
print(f(2))
print(f(3))

the result:

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

the second:

def f(a, L = None):
    if L is None:
        L = []
    L.append(a)
    return L
print(f(1))
print(f(2))
print(f(3))

the result:

[1]
[2]
[3]

So, in the second piece of code, i am confused that after print(f(1)) was executed, print(f(2)) would pass a = 2 and L=[1] to the f(), but why f() didn't get the L=[1]? If L = None in the second piece of code defines the L to None every time when the f() was called, but why L = [] in the first piece of code don't define L to []

Innat
  • 16,113
  • 6
  • 53
  • 101
FriWant
  • 19
  • 4
  • 2
    The first case has a default *mutable* argument, in the second case the argument is *immutable* – Chris_Rands May 24 '18 at 12:18
  • 4
    Possible duplicate of ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – Chris_Rands May 24 '18 at 12:18

1 Answers1

0

Those two examples show how default arguments work behind the scenes: the first one demostrates that default arguments 'live' inside the function definition. Meaning: that the value for L in the first function will only ever be reset if you overwrite the whole function with a def section.

The Same is true for the second implementation BUT since it's None: you have to initialize it while the function body is executed. This leads to a fresh list every time the function is called.

This behaviour can be confusing and lead to strange results which is why i heard from most sources that it is best to avoid the first option and work with None default args.

Hope i could clear things up a bit.

meissner_
  • 556
  • 6
  • 10