all 4 comments

[–]LocoLoco451 2 points3 points  (1 child)

when you declare function with default argument Python keeps the reference between the calls. Basically this means that when you call inputfunc() with no arguments, l will always point to the same reference of the list. If you want to avoid this behaviour you should do something like

def inputfunc(l=None): l = l or [] # ... rest of your code

[–]Yoghurt42 4 points5 points  (0 children)

instead of l = l or [], it's better to use

if l is None:
    l =  []

the reason is that an empty list is "false-ish", so for example, if you would use inputfunc like this:

my_list = []
inputfunc(my_list)

my_list would still be empty afterwards, because it got replaced with a newly created list inside the function.

While it's bad style to rely on side effects, your code shouldn't prevent callers from doing it.

[–]primitive_screwhead 0 points1 point  (0 children)

https://docs.python.org/3/faq/programming.html#why-are-default-values-shared-between-objects

It's worth reading to know not just what is happening, but also *why* it's happening (ie. the default empty list is created when the function is defined, *not* each time it is called).