Fwd: use a loop to create lists

Franz Kelnreiter kelnreiter at gmail.com
Thu Apr 11 08:11:52 EDT 2013


---------- Forwarded message ----------
From: Franz Kelnreiter <kelnreiter at gmail.com>
Date: Thu, Apr 11, 2013 at 2:09 PM
Subject: Re: use a loop to create lists
To: Thomas.Goebel at ohm-hochschule.de


On Thu, Apr 11, 2013 at 1:46 PM, Thomas Goebel <
Thomas.Goebel at ohm-hochschule.de> wrote:

> * On 11/04/2013 13:25, Franz Kelnreiter wrote:
> > On Wed, Apr 10, 2013 at 3:55 PM, Thomas Goebel wrote:
> >>
> >> global_list = {'_'.join(['list', str(i)]):[] for i in range(20)}
> >> global_list_1 = global_list['list_0'] --
> >
> > Sorry Thomas, but you had a typo or in any case a wrong syntax
> > concept in your last posting. If you'd like to use list
> > comprehension it should be written as:
> >
> > mydict = {'_'.join(['list', str(i)]):[x for x in range(20)]}
>
> Hi Franz,
>
> 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)})
>
> Your code creates a dict with one key 'list_19' which value is a list
> with 20 ints if you replace str(i) with str(a).
>
> Regards, Tom
>

Tom,
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)).

So how can you get me on the right direction to make your code running on
my machine?

Thank you, Franz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130411/52821d64/attachment.html>


More information about the Python-list mailing list