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.<br>
<br>What one probably intends by 5 * [ [ ] ] is<br><br>[ [ ] for i in range(5)] <br><br>and this only works because [ ] is a literal, with a new version created each time through the list comprehension.<br><br>Andy<br><br>
<div class="gmail_quote">On Fri, Apr 23, 2010 at 4:41 PM, David MacQuigg <span dir="ltr"><<a href="mailto:macquigg@ece.arizona.edu">macquigg@ece.arizona.edu</a>></span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<div class="im">Mark Engelberg wrote:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
That reminds me of a similar gotcha I've unfortunately run into on<br>
more than one occasion.<br>
<br>
# intialize a to be a list of 5 empty lists<br>
a = 5*[[]]<br>
# push a value onto the first list.<br>
a[0].append(1)<br>
<br>
What's a?<br>
<br>
</blockquote>
<br></div>
The result actually makes sense, although I did guess it wrong. :>(<br>
<br>
>>> a = b = [1,2,3]<br>
>>> c = [a,b] # a list with two references to the same object<br>
<br>
>>> id(c[0])<br>
3626848<br>
>>> id(c[1])<br>
3626848<br>
<br>
>>> c[0][0] = 5<br>
>>> a<br>
[5, 2, 3]<br>
<br>
What is b?<br>
<br>
Would you rather have Python do something different?<br>
<br>
<br>
When taking shortcuts like a = 5*[[]], never trust, always verify.<br>
<br>
-- Dave<div><div></div><div class="h5"><br>
<br>
_______________________________________________<br>
Edu-sig mailing list<br>
<a href="mailto:Edu-sig@python.org" target="_blank">Edu-sig@python.org</a><br>
<a href="http://mail.python.org/mailman/listinfo/edu-sig" target="_blank">http://mail.python.org/mailman/listinfo/edu-sig</a><br>
</div></div></blockquote></div><br><br clear="all"><br>-- <br>Andrew N. Harrington<br> Director of Academic Programs<br> Computer Science Department <br> Loyola University Chicago <br> 512B Lewis Towers (office) <br>
Snail mail to Lewis Towers 416<br> 820 North Michigan Avenue<br> Chicago, Illinois 60611<br><br><a href="http://www.cs.luc.edu/~anh">http://www.cs.luc.edu/~anh</a><br>Phone: 312-915-7982<br>Fax: 312-915-7998<br><a href="mailto:gpd@cs.luc.edu">gpd@cs.luc.edu</a> for graduate administration<br>
<a href="mailto:upd@cs.luc.edu">upd@cs.luc.edu</a> for undergrad administration<br><a href="mailto:aharrin@luc.edu">aharrin@luc.edu</a> as professor<br>