0

I have quite a bit of experience with C/C++ and have recently started coding more often in Python but I am no expert yet. I am noticing this interesting behaviour and I am not exactly sure what to attribute it to. I have a recursive function that looks like this:

def fun(param=[]):
    # do something
    fun()

I notice that, as I recursively enter fun(), the modified list param is 'forwarded' (for lack of a better word) along. I am surprised that I don't need to call fun(param) to carry param from one call to another. Why is that? As a C++ developer, that weirds me out.

  • 1
    This has been discussed at https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument (and many other places). – Amitai Irron May 15 '20 at 22:58
  • Some more places to dig in https://stackoverflow.com/questions/9158294/good-uses-for-mutable-function-argument-default-values and https://stackoverflow.com/questions/19427147/python-recursion-passing-some-value-down-through-the-calls – Gunesh Shanbhag May 15 '20 at 23:01

0 Answers0