In the 5*[[]] example, the issue is again mutable objects. (list * int) does a shallow copy. This is the only thing that makes sense. There is no universal clone operation that you could use instead of the shallow copy. Issues with mutable objects are not going to go away just because we wish they would. I like to be able to write an initialization with immutable objects, like 5 *[None], and would not want to give that up because of the gotcha's with mutable objects.
What one probably intends by 5 * [ [ ] ] is
[ [ ] for i in range(5)]
and this only works because [ ] is a literal, with a new version created each time through the list comprehension.
Andy
Mark Engelberg wrote:The result actually makes sense, although I did guess it wrong. :>(
That reminds me of a similar gotcha I've unfortunately run into on
more than one occasion.
# intialize a to be a list of 5 empty lists
a = 5*[[]]
# push a value onto the first list.
a[0].append(1)
What's a?
>>> a = b = [1,2,3]
>>> c = [a,b] # a list with two references to the same object
>>> id(c[0])
3626848
>>> id(c[1])
3626848
>>> c[0][0] = 5
>>> a
[5, 2, 3]
What is b?
Would you rather have Python do something different?
When taking shortcuts like a = 5*[[]], never trust, always verify.
-- Dave
_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig