List Init Behavior

Michael Tiomkin michael at camelot-it.com
Wed Mar 8 09:41:54 EST 2000


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

  As usual in Python, you can do something like this with a one liner:
l = map(lambda u,z=[None]*x: z+[], range(y))

  Michael




More information about the Python-list mailing list