(question)
Question:
Answer:
Question:
#!/usr/bin/python
a = [1,2,3]
b = a
a += [4]
b = b + [5]
print "a=%s" % a
print "b=%s" % b
Output:
For non-mutable objects, the effect is almost always the same, but mutable objects behave differently. The
Thea=[1, 2, 3, 4] b=[1, 2, 3, 4, 5]
+=
operator does not do the same thing as writing
foo = foo + value
.
For non-mutable objects, the effect is almost always the same, but mutable objects behave differently. The
+=
operator is designed to
change an object in-place, where the longer method will produce a new object
and re-bind the name to the new object. Taking away the syntactic sugar,
the example could be written more explicitly as:
a = [1,2,3] b = a a.__iadd__([4]) b = b.__add__([5])