2

I'm not able to understand the mechanism behind this behavior in python.

def fun(s=[]):
   s.append(1)
   print s

fun()
fun()

Output is:

[1]
[1,1]

Why does python "remember" the value of the list passed on the function?

  • `Actually, this is not a design flaw, and it is not because of internals, or performance. It comes simply from the fact that functions in Python are first-class objects, and not only a piece of code.` – cs95 Oct 31 '17 at 05:54
  • This is explained here: http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments – Sharad Oct 31 '17 at 05:56

0 Answers0