0

I am a beginner to Python. While going over the official introduction https://docs.python.org/2/tutorial/controlflow.html, I couldn't quite understand the last example in section in 4.7.1. Specifically, why does

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

not share values among subsequent calls when the function is evaluated without explicitly providing the default value for L?

Suppose I evaluate f(1) and f(2) in succession. For the first call, L is set to None, the default value, so the if loop condition is satisfied and L is set to []. L is then modified to [1] and returned as output. On the second call, L is still [1] *, which is not None, so the if loop should not be initiated, and I would expect the output to simply be 2 appended to [1], i.e. [1,2], whereas the output is [2].

So * must be false. But when I evaluate print(f(1)), I get [1] as output, not None. Compounding to my confusion is the penultimate example in the same section:

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

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

returns

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

What is going on over here? The website does say default values are only evaluated once, so does the value only carry over when the default value is set to a mutable object, as is the case above with []? If that is so, I would presume None is immutable in the first example, and the value of L that is returned is discarded immediately upon execution and display of the output.

  • You missed the point of "default values are only evaluated once". The default value is defined during compile time, not while the script runs. – Matthias Jun 27 '19 at 09:44
  • @Matthias Then why does the function defined in the second example accumulate arguments passed to it on subsequent calls? – SystematicDisintegration Jun 27 '19 at 09:46
  • *"On the second call, `L` is still `[1]`"* – It's not. It starts out as `None` again and is initialised to `[]` again. It's a local variable, it doesn't keep state beyond one function call. – deceze Jun 27 '19 at 09:46
  • @SystematicDisintegration: In the second example you define a list as the default value. The list itself will not change (same id), but the content of the list is altered. – Matthias Jun 27 '19 at 09:49
  • @deceze In that case, like I asked before, why do the arguments of the second function accumulate on successive calls? If L is indeed a local variable, all previous calls should be irrelevant - upon arbitrary execution without a specified second argument, `L` should be set to `[]`. – SystematicDisintegration Jun 27 '19 at 09:56
  • 1
    You mean *of the __second__ function*? See the duplicate then, it's well explained there. – deceze Jun 27 '19 at 10:00

0 Answers0