List weirdness - what the heck is going on here?
apt.shansen at gmail.com
Thu Jan 28 03:22:25 CET 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 = []*2
> self.data = [ 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 . 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
 twice, which you can see as:
print self.data is self.data
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  each time
it loops over your xrange.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list