Bug or feature?

Skip Montanaro skip at pobox.com
Fri Jan 16 17:51:15 EST 2004


    >> Of course, it should be noted that, in Python, "a += b" is only
    >> sometimes synonymous with "a = a + b".  The rest of the time, it's
    >> hard to say what it is synonymous with :)

    James> What do you have in mind?  J.

For immutable objects, += works as you'd expect: return a new object,
leaving the old object unchanged.  That's not the case for mutable objects,
to wit:

    >>> foo = [1]
    >>> bar = foo
    >>> foo += [2]

The object referenced by foo is modified in-place...

    >>> bar
    [1, 2]
    >>> foo = foo + [2]

Here foo is bound to a new object, leaving the old object (still referenced
by bar) unchanged.

    >>> foo
    [1, 2, 2]
    >>> bar
    [1, 2]

Skip




More information about the Python-list mailing list