List Question

Steven D. Majewski sdm7g at Virginia.EDU
Fri Jul 20 13:47:07 EDT 2001


The new list comprehensions work nice for that:

>>> a = [ [0]*3 for x in range(3) ]
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[1][1] = 9999
>>> a
[[0, 0, 0], [0, 9999, 0], [0, 0, 0]]


You can also use a loop or a lambda:

>>> l = []
>>> for i in range(3):
...     l.append( [0]*3 )
... 

>>> map( lambda i: [0]*3, range(3) )

The essential thing is that the expression that creates the 
inner list ([0]*3) gets evaluated multiple times, not just 
replicated. Replicating the inner list with "*" :

>>> x = [[0]*3]*3
>>> x[1][1] = 9999
>>> x
[[0, 9999, 0], [0, 9999, 0], [0, 9999, 0]]


is what gives you multiple copies of the SAME list. 

-- sdm





More information about the Python-list mailing list