Augument assignment versus regular assignment

Frank Millman frank at chagford.com
Sun Jul 9 02:02:04 EDT 2006


nagy wrote:
> Thanks, Kirk.
> I considered the += as only a shorthand notation for the assignment
> operator.
> Since for lists + is simply a concatetation, I am not sure it x=x+[2]
> is creating a brand
> new list. Could you refer me to any documentation on this?
> Thanks,
> Nagy

My habit is to check the id.

>>> x = [1,2]
>>> id(x)
-1209327188
>>> x += [4]
>>> x
[1,2,4]
>>> id(x)
-1209327188
>>> x = x + [6]
>>> x
[1,2,4,6]
>>> id(x)
-1209334664

So it looks as if x +=  [] modifies the list in place, while x = x + []
creates a new list.

I am not sure if this is 100% guaranteed, as I have noticed in the past
that id's can be reused under certain circumstances. Perhaps one of the
resident gurus can comment.

Frank Millman




More information about the Python-list mailing list