List weirdness - what the heck is going on here?

Stephen Hansen apt.shansen at gmail.com
Wed Jan 27 21:22:25 EST 2010


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

> But suppose I replace the line


>  self.data = [[0]]*2
>
> with
>
>  self.data = [[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 self.data[0] is self.data[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.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100127/10876ca8/attachment-0001.html>


More information about the Python-list mailing list