What is the difference between “append” and “+” in python?

  • A+
Category:Languages

I don't know what is difference between f() and g().

In function f, list L is accumulated whenever function is called..

but in function g, it does not..

def f(a, L=[]):     L.append([2]);     print(L);  def g(a, L=[]):     L = L+[2];     print(L);  print("f:") f(1) # [[2]] f(2) # [[2], [2]] f(3) # [[2], [2], [2]]  print("g:") g(1) # [2] g(2) # [2] g(3) # [2] 

 


The strange behaviour you can see with your example is not due to the difference between the + operator and the append function.

It is due to the fact that you assigned a list as a default value to a function parameter and you assign the result of a concatenation in a local variable in g.


That is not so widely known but defining a list (or a dict or an object) as a parameter default value is probably not what you want. When you do so, the list used as default value for the parameter is shared across all function calls.

So for the f function:

  1. you call it a first time without the L parameter, the default value ([]) is taken and appended with 2. So it becomes [2]
  2. you call it a second time without the L parameter, the default value is taken but it is now [2]. 2 is appended again and it becomes [2, 2] wich is now the default value of your function.

for the g function:

  • as for the f function, the default value is an empty list, but this list is never modified. The fact is that the result of L + [2] is affected to a local variable L and the default value of the function is never modified. So when you call the function again, the default value is always [].
  • As Klimenkomud said in his answer using the += operator instead of a concatenation and an assignation actually modifies the default value of the L parameter. If you do so, the g function will behave like the f function.

As a conclusion, using an empty list as a parameter default value is almost never what you want. Instead, you probably want this:

def f(a, L=None):     L = L or []     ... 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: