List Init Behavior

Kevin Digweed Kevin.Digweed at MERANT.com
Wed Mar 8 13:25:39 CET 2000


Gene, try this:

l = map(lambda n: [0]*2, [None]*3)

Or there's the more general/readable generator function:

def listoflists(width, height, init=None):
       return map(lambda n,i=init: [i]*n, [width]*height)

... which will probably be faster using a loop instead of map/lambda.

Gene Chiaramonte wrote:
> 
> When initializing a list of lists, I came across this behavior.
> 
> >>> l = [[0]*2]*3
> >>> l
> [[0, 0], [0, 0], [0, 0]]
> >>> l[1][1] = 5
> >>> l
> [[0, 5], [0, 5], [0, 5]]
> 
> What I really want to do is quickly init a large list of lists where each
> row is its own list. Not all rows pointing to the same list as above. Any
> ideas?
> 
> This works - but I like the one line syntax better.
> x = 5
> y = 10
> l = [0]*y
> for i in range(y):
>     l[i] = [0]*x
> 
> Thanks,
> 
> Gene



More information about the Python-list mailing list