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

On Fri, Apr 23, 2010 at 4:41 PM, David MacQuigg <macqu...@ece.arizona.edu>wrote:

> Mark Engelberg wrote:
>
>> 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?
>>
>>
>
> The result actually makes sense, although I did guess it wrong. :>(
>
> >>> 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
>



-- 
Andrew N. Harrington
 Director of Academic Programs
 Computer Science Department
 Loyola University Chicago
 512B Lewis Towers (office)
 Snail mail to Lewis Towers 416
 820 North Michigan Avenue
 Chicago, Illinois 60611

http://www.cs.luc.edu/~anh
Phone: 312-915-7982
Fax:    312-915-7998
g...@cs.luc.edu for graduate administration
u...@cs.luc.edu for undergrad administration
ahar...@luc.edu as professor
_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig

Reply via email to