0
def f1(a,L=[]):
    if a==1:
        print(a,L)
    else:
        L.append(a)
    return L

def f2(a,L=[]):
    if a==1:
        print(a,L)
    else:
        L=[3]
    return L

calling these two functions yield these results:

f1(2) -> [2]

f1(1) -> 1 [2]

f2(2) -> [3]

f2(1) -> 1 []

That really makes me confused, if L will not loss if value after calling, why f2(1) does not return 1 [3]? Anyone can explain the argument value store or initialization schema in python?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • function has it is own scope and L will be generated every time and be in the scope of the function, your printed value make sense. – Fady Saad Aug 24 '17 at 23:17
  • 1
    `L=[3]` creates a *new object* `[3]` and assigns it to local name `L`. The original list is not mutated and the name `L` associated with the original list is not in scope. That `L` name is part of the function definition. That function definition is used to create a separate local name `L` at the time the function is called. – Steven Rumbalski Aug 24 '17 at 23:22

0 Answers0