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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With