[Tutor] Lists on the fly?

Bob Gailer bgailer at alum.rpi.edu
Fri Dec 22 18:31:00 CET 2006


Carlos wrote:
> Hello,
>
> I am wondering if it is possible to create lists on the fly. 
This is an FAQ. The more general question is "Can I create variables 
with dynamically generated names." The answers are:
(1) Yes
(2) This is rarely a good idea.
The preferred solution is to use a dict or list, each item of which is 
one of the "variables" you want to create. Use a list if the names, like 
yours, are of the form

list_1, list_2, ..., list_n. Then refer to the list with n as the list index. To apply to your example:

list_ = [[] for x in xrange(5)] # creates [[], [], [], [], []].
Then you may refer to list_[0], list_[1], etc.
> 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?
>
> Thanks in advance,
> And Merry Christmas,
> Carlos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454



More information about the Tutor mailing list