Augument assignment versus regular assignment
Kirk McDonald
kirklin.mcdonald at gmail.com
Fri Jul 7 23:41:08 EDT 2006
nagy wrote:
> I do the following. First create lists x,y,z. Then add an element to x
> using the augumented assignment operator. This causes all the other
> lists to be changed also.
> But if I use the assignment x=x+[4] instead of using the augumented
> assignment, the y and z lists do not change.
> Why is that?
> This does not happen when I work with integer data type for example, as
> shown below.
>
> Thanks for your help
> Nagy
>
>
>>>>x=y=z=[]
In this example, the '[]' creates a new list object. x, y, and z are all
set to reference that object.
>>>>x+=[2]
This does an "in-place" operation on that list, modifying (or
"mutating") the object directly.
>>>>x
>
> [2]
>
>>>>y
>
> [2]
>
>>>>z
>
> [2]
>
>>>>x=x+[4]
This creates a new list that is the concatenation of the list created
above (the list [2]) with a new list (the list [4]). This brand new list
is bound to the name 'x'. The names 'y' and 'z' are left unchanged. That
is, they still point to the original list.
>>>>
>>>>x
>
> [2, 4]
>
>>>>y
>
> [2]
>
>>>>z
>
> [2]
>
>>>>a=b=4
This binds the names 'a' and 'b' to the integer object 4.
>>>>b
>
> 4
>
>>>>a+=2
This attempts to mutate the integer object 4, by adding 2 to it.
However, numbers in Python are immutable, and so the in-place operation
fails. Thus, it creates a new integer object equal to 6 (actually,
CPython keeps a cache of certain smaller integer objects and reuses
them, but this does not matter in practice). This new integer object is
bound to the name 'a'. The name 'b' remains bound to the original 4 object.
>>>>a
>
> 6
>
>>>>b
>
> 4
>
More information about the Python-list
mailing list