Fwd: use a loop to create lists

Thomas Goebel Thomas.Goebel at ohm-hochschule.de
Thu Apr 11 09:43:09 EDT 2013


* On 11/04/2013 14:11, Franz Kelnreiter wrote:
> On Thu, Apr 11, 2013 at 1:46 PM, Thomas Goebel wrote:
> 
>> global_list = {'_'.join(['list', str(i)]):[] 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:
> 
> [a for a in range(20)] for i in range(20)
> 
> I get a syntax error, as I exepected (Python 2.6.4 (r264:75708, Oct 26
> 2009, 08:23:19)).

Sorry Franz,

as you are using python 2.6 you have to use

d1 = dict(('list_' + str(i), []) for i in range(3))
d2 = dict(('list_' + str(i), [m for m in range(3)]) for i in range(3))

like stated here:
http://stackoverflow.com/questions/1747817/python-create-a-dictionary-with-list-comprehension



More information about the Python-list mailing list