One-step multiples list generation?

Rocco Moretti roccomoretti at hotpop.com
Tue Jan 3 19:06:45 CET 2006


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], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], 
[], [], []]




More information about the Python-list mailing list