Something in the function tutorial confused me.

David Wahler dwahler at gmail.com
Sat Aug 11 17:36:58 EDT 2007


On 8/11/07, Gregory D. Weber <spottedMetal at gmail.com> wrote:
> I too thought += was an assignment.  And it bit me very painfully a few weeks ago.
>
> If it's an assignment, then wouldn't "x += y" mean the same thing as "x = x + y"?
>
> If so, why does an assignment to variable a, below, have the *side effect* of changing variable b ... ?
>
> >>> a = [1, 2, 3]
> >>> b = a
> >>> b
> [1, 2, 3]
> >>> a += [4]
> >>> a
> [1, 2, 3, 4]
> >>> b
> [1, 2, 3, 4]
>
> ... but using the "x = x + y" style, the assignment to variable c, below, does *not* have a side effect on variable d (as indeed it should not!)?
>
> >>> c = [1, 2, 3]
> >>> d = c
> >>> d
> [1, 2, 3]
> >>> c = c + [4]
> >>> c
> [1, 2, 3, 4]
> >>> d
> [1, 2, 3]

>>> help(list.__iadd__)
Help on wrapper_descriptor:

__iadd__(...)
    x.__iadd__(y) <==> x+=y

For mutable (built-in) objects such as lists, __iadd__ modifies the
list and then returns the list object; for immutable objects, __iadd__
is equivalent to __add__ and just returns the new value. However, in
both cases, the result is then rebound to x. This can lead to some
behaviors you might not normally expect:

>>> t = ([],)
>>> t[0] += [1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t
([1],)

-- David



More information about the Python-list mailing list