List weirdness - what the heck is going on here?

Stephen Hansen apt.shansen at
Thu Jan 28 03:22:25 CET 2010

On Wed, Jan 27, 2010 at 6:06 PM, Rotwang <sg552 at> wrote:

> But suppose I replace the line

> = [[0]]*2
> with
> = [[0] for c in xrange(2)]

The first line does not do what you think it does: it doesn't make a copy of
that internal [0]. Python almost never implicitly copies anything, things
that look like they may make a copy of a mutable object-- usually don't,
unless there's something very explicit in the action that says 'making a new
object out of that other object'

What it is doing is creating a list which contains a reference to the same
[0] twice, which you can see as:

print[0] is[1]

The "is" operator doesn't test equality, but precise identity-- those two
objects are exactly the same. So when you loop over later to insert data,
what you're doing is inserting the same data into the same exact list...
that just happens to be known by two different names right now. :)

The list comprehension, on the other hand, is creating a new [0] each time
it loops over your xrange.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list