One-step multiples list generation?

Rocco Moretti roccomoretti at hotpop.com
Tue Jan 3 19:09:49 CET 2006


Rocco Moretti wrote:
> Damien Wyart wrote:
> 
>> * Efrat Regev <efrat_regev at yahoo.com> in comp.lang.python:
>>
>>> Suppose I have some non-numerical Foo and would like to create a list
>>> of 20 Foo-s. Is there a one-step method (not a loop) of doing so?
>>
>>
>>
>> Maybe :
>>
>> [ Foo ] * 20
>>
>> or, more verbose,
>>
>> [ Foo for _ in range(20) ]
>>
> 
> If Foo is mutable, keep this in mind:
> 
>  >>> a = [ [] ]*20 # A list of 20 empty lists
>  >>> print id(a[0]) == id(a[1])
> True
>  >>> a[0].append(1)
>  >>> print a
> [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], 
> [1], [1], [1], [1], [1], [1]]
>  >>>
>  >>> b = [ [] for _ in range(20) ] # A list of 20 empty lists
>  >>> print id(b[0]) == id(b[1])
> False
>  >>> b[0].append(1)
>  >>> print b
> [[1], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], 
> [], [], []]
> 

Oh, but also:

 >>> Foo = []
 >>> c = [ Foo for _ in range(20) ] # A list of 20 empty lists
 >>> print id(c[0]) == id(c[1])
True
 >>> c[0].append(1)
 >>> print c
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], 
[1], [1], [1], [1], [1], [1]]

(The difference with the 'b' case is that a new list is created each 
"time around", in the other cases, the same list is reused.



More information about the Python-list mailing list