Multi-dimensional list initialization trouble

J

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
 
S

Scott David Daniels

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
(e-mail address removed)
 
T

trebucket

An expression like this creates a list of integers:
[0, 0]

But an expression like this creates list of references to the list
named `foo':
[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)]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,263
Messages
2,571,312
Members
47,988
Latest member
HarryBeck

Latest Threads

Top