Multi-dimensional list initialization trouble

trebucket at gmail.com trebucket at gmail.com
Thu May 25 17:38:34 EDT 2006


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)]




More information about the Python-list mailing list