Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python default params confusion

Tags:

python

I just started learning Python and I'm confused about this example:

def append_to(element, to=None):
    if to is None:
        to = []
    to.append(element)
    return to

If to was initialized once, wouldn't to not be None the 2nd time it's called? I know the code above works but can't wrap my head around this "initialized once" description.

like image 331
dreamfly Avatar asked Oct 18 '22 14:10

dreamfly


1 Answers

def append_to(element, to=None):
    to = ...

to here becomes a local variable and is assigned to a list, and is deallocated if you don't assign return value to another variable.

If you want to staying alive for subsequent calls to append_to you should do:

def append_to(element, to=[]):
    to.append(element)
    return to

Demo:

>>> lst = append_to(5)
>>> append_to(6)
>>> append_to(7)
>>> print lst
[5, 6, 7]
like image 51
Ozgur Vatansever Avatar answered Oct 21 '22 04:10

Ozgur Vatansever