use a loop to create lists

Thomas Goebel Thomas.Goebel at ohm-hochschule.de
Thu Apr 11 08:57:41 EDT 2013


* On 11/04/2013 14:11, Franz Kelnreiter wrote:
> On Thu, Apr 11, 2013 at 1:46 PM, Thomas Goebel wrote:
>>
>> the difference between your and my code is that
>>
>> global_list = {'_'.join(['list', str(i)]):[] for i in range(20)}
>>
>> creates a dict 'global_list' which has 20 keys named from 'list_0' to
>> 'list_19'. The value for all keys is an empty list. If you want to
>> create i.e. 20 keys which value is a list with 20 ints you have to use
>>
>> global_list = ({'_'.join(['list', str(i)]):[a for a in range(20)] for
>>     i in range(20)})
>
> Thanks for your explanation, I think I know what you want to do and I would
> very much like to understand your code in detail - maybe I am too stupid -
> but when I execute the value part of your code construct:

This code
> [a for a in range(20)] for i in range(20)

won't run because you you didn't define 'i'!

[a for a in range(3)]

will return a list
[0, 1, 2]


To get a dict with n keys we can use a for-loop, too:

d = {}
for n in range(3):
    # Create keys 'list_0' to 'list_n'
    d['list_' + str(n)] = []

So we finally get:
d.keys()
['list_2', 'list_1', 'list_0']

d.values()
[[], [], []]


Now we create a dict with n keys and for every key n we set the value
to a list of m ints:

e = {}
for n in range(3):
    # Create keys 'list_0' to 'list_n'
    e['list_' + str(n)] = []
    for m in range(3):
        # Create a list [0, 1, 2] for every key of e
        e['list_' + str(n)].append(m)

The results is as follows:
e.keys()
['list_2', 'list_1', 'list_0']

e.values()
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Which is the same as:
f = {'list_' + str(n):[m for m in range(3)] for n in range(3)}

I double checked the code and everything is working fine for me. Maybe
you forgot some braces?

P.S: I'm running on python 2.7.4:
'2.7.4 (default, Apr  6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)]'



More information about the Python-list mailing list