Following are three python codes:
======= No. 1 =======
def foo(x, items=[]):
items.append(x)
return items
foo(1) #return [1]
foo(2) #return [1,2]
foo(3) #return [1,2,3]
====== No. 2 ========
def foo(x, items=None):
if items is None:
items = []
items.append(x)
return items
foo(1) #return [1]
foo(2) #return [2]
foo(3) #return [3]
====== No. 3 =======
def foo(x, items=[]):
items.append(x)
return items
foo(1) # returns [1]
foo(2,[]) # returns [2]
foo(3) # returns [1,3]
For code No.1, since the value of items
is not provided, I think it should take a default value of [] all the time. But the parameter items
behaves like a static variable, retaining its value for subsequent use. The code of No.2 executes as I expected: each time foo is invoked, items
take the default value None
. As for code No.3, I totally have no idea. Why the above three pieces of codes execute so differently? Can you explain? Thank you.
PS: I'm using python 3.3.1