[Tutor] Lists on the fly?

Kent Johnson kent37 at tds.net
Fri Dec 22 17:37:50 CET 2006

Carlos wrote:
> Hello,
> I am wondering if it is possible to create lists on the fly. The script 
> that I'm working on needs a number of parameters, one of those is 
> population, and this corresponds to the number of solutions that a 
> genetic algorithm generates on each generation (iteration). The thing is 
> that I need to generate one list for each population member and then 
> append the corresponding population members to that particular list.
> This is only so you can have an idea:
> for i in range(5):
>     'list_%i' % (i) = []
> or:
> for i in range(5):
>     lista_+'%i' % (i) = []
> :-[
> Is this possible?

It is possible, using exec, but it is not the right solution to your 
problem. You want a bunch of lists each associated with a name. The way 
to do this is put the lists in a dict; the name is the key, the list is 
the value. Your example would look like this:

lists = {}
for i in range(5):
   lists['list_%i' % (i)] = []


More information about the Tutor mailing list