Multi-dimensional list initialization trouble

2006-05-25 Thread jonkje
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
>>> foo
[[0, 0], [0, 0]]
>>> baz
[[0, 0], [0, 0]]
>>> foo[0][0]=1
>>> baz[0][0]=1
>>> foo
[[1, 0], [0, 0]]
>>> baz
[[1, 0], [1, 0]]

Why on earth does foo and baz behave differently??

Btw.:
Python 2.4.1 (#1, Apr 10 2005, 22:30:36)
[GCC 3.3.5] on linux2

--- Jon Øyvind

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-dimensional list initialization trouble

2006-05-25 Thread Scott David Daniels
[EMAIL PROTECTED] 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
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-dimensional list initialization trouble

2006-05-25 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Hello I found this very strange; is it a bug, is it a "feature", am I
> being naughty or what?

the repeat operator (*) creates a new list with references to the same
inner objects, so you end up with a list containing multiple references 
to the same list.  also see:

 http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-dimensional list initialization trouble

2006-05-25 Thread trebucket
An expression like this creates a list of integers:
>>> [0] * 2
[0, 0]

But an expression like this creates list of references to the list
named `foo':
>>> foo = [0, 0]
>>> baz = [foo] * 2
[foo, foo]

So, setting baz[0][0] = 1, is really setting foo[0] = 1.  There is only
one instance of foo, but you have multiple references.

Try a list comprehension to get the result you want:
>>> foo = [[0 for ii in range(2)] for jj in range(2)]

-- 
http://mail.python.org/mailman/listinfo/python-list