0

How value of list "values" are retained outside the function "f" in example below ?

def f(i, values = []):
    values.append(i)
    print (values)
    return values
f(1)
f(2)
f(3)

The output is not [1] [2] [3] but [1] [1, 2] [1, 2, 3]. Im confused, how values hold its value outside the function ?

If Im trying to access it outside the function , python(2.7 and 3.x) gives me NameError

   def f(i, values = []):
        values.append(i)
        print (values)
        return values
    f(1)
    print(values)
    f(2)
    print(values)
    f(3)
    print(values)

 python3 test2.py 
[1]
Traceback (most recent call last):
  File "test2.py", line 6, in <module>
    print(values)
NameError: name 'values' is not defined

Thank you !

Andy
  • 2,706
  • 3
  • 13
  • 22
  • 2
    Better duplicate: [Method's default parameter values are evaluated \*once\*](https://stackoverflow.com/q/1367883/4518341) @Mark – wjandrea Oct 31 '20 at 22:54
  • @wjandrea I actually didn't know about that one. I'll start using that question instead going forward. Thank you. – Carcigenicate Oct 31 '20 at 23:02
  • 1
    There are not many things I dislike about Python, but this is one of them. A poor design for the implementation of optional arguments. – Frank Yellin Oct 31 '20 at 23:23

0 Answers0