The += operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here?
class foo:
bar = []
def __init__(self,x):
self.bar += [x]
class foo2:
bar = []
def __init__(self,x):
self.bar = self.bar + [x]
f = foo(1)
g = foo(2)
print f.bar
print g.bar
f.bar += [3]
print f.bar
print g.bar
f.bar = f.bar + [4]
print f.bar
print g.bar
f = foo2(1)
g = foo2(2)
print f.bar
print g.bar
OUTPUT
[1, 2]
[1, 2]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3]
[1]
[2]
foo += bar seems to affect every instance of the class, whereas foo = foo + bar seems to behave in the way I would expect things to behave.
The += operator is called a "compound assignment operator".
For the general case, see Scott Griffith's answer. When dealing with lists like you are, though, the
+=operator is a shorthand forsomeListObject.extend(iterableObject). See the documentation of extend().The
extendfunction will append all elements of the parameter to the list.When doing
foo += somethingyou're modifying the listfooin place, thus you don't change the reference that the namefoopoints to, but you're changing the list object directly. Withfoo = foo + something, you're actually creating a new list.This example code will explain it:
Note how the reference changes when you reassign the new list to
l.As
baris a class variable instead of an instance variable, modifying in place will affect all instances of that class. But when redefiningself.bar, the instance will have a separate instance variableself.barwithout affecting the other class instances.