Python - mutable default arguments to functions -


i going through https://docs.python.org/3.5/tutorial/controlflow.html#default-argument-values. modified example there little bit below:

x = [4,5] def f(a, l=x):     l.append(a)     return l  x = [8,9] print(f(1,[6,7])) print(f(2)) print(f(3)) 

the output got was:

[6, 7, 1] [4, 5, 2] [4, 5, 2, 3] 

now, per understood python docs:

  1. the default values evaluated @ point of function definition in defining scope. so, l = [4,5]

  2. after 1st call f(), l = [6,7,1]. fine.

  3. what don't understand output after 2nd call f(). if l's value shared between calls f(), output after 2nd function call should [6,7,1,2]. l's value shared between 2nd , 3rd call f() not between 1st , 2nd call.

this because each time call f performs l=x, x default value l on argument list of f.

so every time appends x.


Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -