0

I have a piece of code as below:

def f(x,l=[]):
    for i in range(x):
        l.append(i*i)
    print(l) 

f(2)
f(3)

Why it gives as:

 [0, 1]
 [0, 1, 0, 1, 4]

for f(3) ? why it is storing value of l ? Isn't it supposed to be local temporary variable ?

fafl
  • 7,222
  • 3
  • 27
  • 50
Webair
  • 95
  • 1
  • 6
  • 1
    Please fix the indentation – yinnonsanders Nov 14 '17 at 16:31
  • Please check your indentation, the code you posted will not work. – Davy M Nov 14 '17 at 16:31
  • A simpler explanation can be found in [this question](https://stackoverflow.com/questions/15377050/pass-list-to-function-by-value) rather than the one posted. – Davy M Nov 14 '17 at 16:33
  • TL; DR default args are evaluated when the function is _defined_. They are _not_ evaluated each time the function is called. – PM 2Ring Nov 14 '17 at 16:34
  • Even its a duplicate, a workaround is `'def f(x,l=None):\n if l is None :\n l=[]\n for i in range(x):\n l.append(i*i)\n print(l)\n'` – B. M. Nov 14 '17 at 16:38
  • @B.M. That works, but there's no need here for `l` to be an arg at all, it can just be a normal local variable. – PM 2Ring Nov 14 '17 at 16:40
  • @PM 2Ring : I think OP wants in some case add some numbers in the output . – B. M. Nov 14 '17 at 16:44
  • Why it is different from: `code def foo(i, x=[]): x.append(i*i) return x for i in range(3): y = foo(i) print(y)` ' – Webair Nov 14 '17 at 17:19

0 Answers0