use a loop to create lists

Thomas Goebel Thomas.Goebel at ohm-hochschule.de
Thu Apr 11 10:33:21 EDT 2013


* On 11/04/2013 16:11, Franz Kelnreiter wrote:
> On Thu, Apr 11, 2013 at 2:57 PM, Thomas Goebel <
> Thomas.Goebel at ohm-hochschule.de> wrote:
> 
>> ...
>> Which is the same as:
>> f = {'list_' + str(n):[m for m in range(3)] for n in range(3)}
>>
> [...]
> But didnt you miss square brackets:
> 
> f = {'list_' + str(n):[[m for m in range(3)] for n in range(3)]}

If i try your code i get a dict with key 'list_2' which value is a
list of three lists.

Maybe this occurs because we're using different python versions?! I
never used python<2.7!

Have you tried this one

d2 = dict(('list_' + str(i), list(range(3))) for i in range(3))

with Chris' simplification:

* On 11/04/2013 15:22, Chris Angelico wrote:
> On Thu, Apr 11, 2013 at 10:57 PM, Thomas Goebel wrote:
>> [a for a in range(3)]
>>
>> will return a list
>> [0, 1, 2]
>
> Simplification possible: That's the same as:
>
> list(range(3))
>
>> f = {'list_' + str(n):[m for m in range(3)] for n in range(3)}
>
> Meaning that this can be simplified too:
>
> f = {'list_' + str(n):list(range(3)) for n in range(3)}














More information about the Python-list mailing list