Assignment always changes

Assignment always causes a name to refer to a different object (that is, it rebinds), even if the object is mutable. So if you use assignment (=) inside the function rather than the append() method, mylist doesn't accumulate arguments.

>>> def f(q, mylist=[]): ... mylist = mylist + q

... return mylist

>>>

a =

[1]

>>>

f(a)

[1]

>>>

a =

[2]

>>>

f(a)

[2]

Was this article helpful?

0 0

Post a comment