Could someone explain this multidimensional list behaviour?
Thomas Jensen
thomasNO at SPAM.obscure.dk
Fri Nov 23 04:14:51 EST 2001
lrl at ou.edu (L) wrote in
news:e5f40188.0111222310.5001b6e2 at posting.google.com:
> 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]]
[snip]
> So what is the easy way to allocate an n x n matrix with unique
> values?
There was a discussions very recently discussing this, but I was unable
to find it :-)
>>> spam = [[0 for i in range(3)] for j in range(3)]
>>> spam[0][1] = 1
>>> spam
[[0, 1, 0], [0, 0, 0], [0, 0, 0]]
--
mvh
Thomas Jensen
More information about the Python-list
mailing list