Could someone explain this multidimensional list behaviour?

L lrl at ou.edu
Fri Nov 23 02:10:44 EST 2001


Greetings from a long time java programmer jumping ship,

I'm not having trouble getting around this behavior:

>>> spam = [[0] * 3] * 3
>>> spam
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> spam[0][1] = 1
>>> spam
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]

I was expecting after making the assignment to get this:
[[0, 1, 0], [0, 0, 0], [0, 0, 0]]

After flipping through my O'Reilly I know it has to do with the *
operator, but don't know how otherwise allocate an n x n "array" type
of structure beforehand with each element having a unique pointer,
without using some sort of ridiculous two loop setup and appends like
the following.

>>> spam = []
>>> for y in range(10):
	inner = []
	for x in range(10):
		inner.append(0)
	spam.append(inner)
	del inner

>>> spam
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0,
0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0,
0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0,
0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0,
0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

So what is the easy way to allocate an n x n matrix with unique
values?

Thanks!



More information about the Python-list mailing list