Beginner Question

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jun 1 23:53:59 EDT 2016


On Thursday 02 June 2016 10:55, Marcin Rak wrote:

> Hi to all
> 
> I have a beginner question to which I have not found an answer I was able to
> understand.  Could someone explain why the following program:
> 
> def f(a, L=[]):
>     L.append(a)
>     return L


The default value is set once, and once only, so you get the same list each 
time, not a new empty list.

Default values in Python are sort of like this:

HIDDEN_DEFAULT_VALUE = []  # initialised once
def f(a, L):
    if L is not defined:
        L = HIDDEN_DEFAULT_VALUE
    L.append(a)
    return L


except that HIDDEN_DEFAULT_VALUE is not actually a global variable. Every 
function gets its own storage for defaults. The technical term for this is 
"early binding of default values".

If you want to get a new, fresh list each time ("late binding of default 
values") you should use a sentinel value:


def f(a, L=None):
    if L is None:
        L = []  # new, fresh list each time
    L.append(a)
    return L




-- 
Steve



More information about the Python-list mailing list