Luke Lee

Software Engineer

Web + Desktop + Science

Fork me on Github

Beware of subtle python list semantics

Here's a quiz:

x = [1]
y = [2]
print id(x)

x += y
print x, id(x)

x = [1]
y = [2]
print id(x)

x = x + y
print id(x)

Do += or + create a new object or update the existing one in place? Seems a bit ambiguous and the answer was somewhat unexpected, at least for me.

Keep in mind += is a shorthand for x.extend(y).

I would be curious to know why the Python language was designed with this little 'trick.' It seems like this blatantly violates the 'There should be one-- and preferably only one --obvious way to do it.' mantra from The Zen of Python.

There is a lot of good information associated with this question so make sure to scan through the whole thread. This answer has some nice insight into the special method implementation and design.

The design makes sense but this is definitely something to keep in mind when using the += operator.

Published: 08-03-2012 21:31:00

lukelee.net