Multi-dimensional list initialization trouble

Scott David Daniels scott.daniels at acm.org
Thu May 25 17:33:31 EDT 2006


jonkje at gmail.com wrote:
> Hello I found this very strange; is it a bug, is it a "feature", am I
> being naughty or what?
> 
>>>> foo = [[0, 0], [0, 0]]
>>>> baz = [ [0]*2 ] * 2
>...
> Why on earth does foo and baz behave differently??

This is a frequently made mistake.
try also:
 >>> bumble = [[0]*2 for 0 in xrange(2)]

Think hard about why that might be.
Then try:

 >>> [id(x) for x in foo]
 >>> [id(x) for x in baz]
 >>> [id(x) for x in bumble]

Now check your upper scalp for lightbulbs.

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list