I was shocked to find out that a += b
behaves differently from a = a + b
in my code, and I am able to reduce the issue to the following simple question:
Let's say I have a function g
that depends on f
(another function), x
, y
and lst
(a list). Here I provide two versions of f
, one using lst = lst + [y]
, the other using lst += [y]
def f1(x, y, lst=[]):
lst.append(x)
lst = lst + [y]
return lst
def f2(x, y, lst=[]):
lst.append(x)
lst += [y]
return lst
def g(f, x, y, lst=[]):
return f(x, y, lst) + lst
However, I am getting different results:
print(g(f1, 1, 2, [3, 4]))
# [3, 4, 1, 2, 3, 4, 1]
print(g(f2, 1, 2, [3, 4]))
# [3, 4, 1, 2, 3, 4, 1, 2]
Can someone explain what is going on here?