[Edu-sig] teaching Python

David MacQuigg macquigg at ece.arizona.edu
Fri Apr 23 23:41:32 CEST 2010


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



More information about the Edu-sig mailing list