x += ... is not the same than x = x + ... if x is mutable

J

Jussi Piitulainen

Hi,

I thought that x += ... was the same than x = x + ..., but today I
have realized it is not true when operating with mutable objects.

In Python 3.3 or 2.7 IDLE (Windows) compare:
a = [3]
b = a
a = a + [1]
b
[3]

and
a = [3]
b = a
a += [1]
b
[3, 1]

Is this behaviour explained in the Python documentation?

Yes, it's documented in the language reference, specifically in the
latter half of the paragraph quoted below.

<http://docs.python.org/3/reference/simple_stmts.html#assignment-statements>

# An augmented assignment expression like x += 1 can be rewritten as x
# = x + 1 to achieve a similar, but not exactly equal effect. In the
# augmented version, x is only evaluated once. Also, when possible,
# the actual operation is performed in-place, meaning that rather than
# creating a new object and assigning that to the target, the old
# object is modified instead.
 
N

Nobody

I thought that x += ... was the same than x = x + ..., but today I have
realized it is not true when operating with mutable objects.

It may or may not be the same. x += y will invoke x.__iadd__(y) if x has
an __iadd__ method, otherwise x + y will be evaluated and the result
assigned to x.

In the first case, x will always continue to refer to the same object
(i.e. id(x) won't change). In the second case, x will typically (but not
always) refer to a different object.
 
C

Colin J. Williams

It may or may not be the same. x += y will invoke x.__iadd__(y) if x has
an __iadd__ method, otherwise x + y will be evaluated and the result
assigned to x.
Does this depend on whether Py27 or Py32 is used?

Colin W.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top