copy on write

Chris Angelico rosuav at gmail.com
Fri Jan 13 07:30:56 EST 2012


On Fri, Jan 13, 2012 at 11:10 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
>>>> z = [x, y]  # z is a list containing the same sublist twice
>>>> z[0].append(23)
>>>> print z
> [[42, 23], [42, 23]]
>
> When you work with floats, ints or strings, you don't notice this because
> those types are immutable: you can't modify those objects in place. So
> for example:
>
>>>> a = 42  # binds the name 'a' to the object 42
>>>> b = a  # a and b point to the same object
>>>> a += 1  # creates a new object, and binds it to a
>>>> print b  # leaving b still pointing to the old object
> 42

I was about to say that it's a difference between ".append()" which is
a method on the object, and "+=" which is normally a rebinding, but
unfortunately:

>>> a=[]
>>> b=a
>>> a+=[1]
>>> a
[1]
>>> b
[1]
>>> b+=[2]
>>> a
[1, 2]
>>> a
[1, 2]
>>> a=a+[3]
>>> a
[1, 2, 3]
>>> b
[1, 2]

(tested in Python 3.2 on Windows)

It seems there's a distinct difference between a+=b (in-place
addition/concatenation) and a=a+b (always rebinding), which is sorely
confusing to C programmers. But then, there's a lot about Python
that's sorely confusing to C programmers.

ChrisA



More information about the Python-list mailing list