use a loop to create lists

rusi rustompmody at gmail.com
Wed Apr 10 11:31:50 EDT 2013


On Apr 10, 1:40 pm, martaamu... at gmail.com wrote:
> Hi!
>
> I would like to create a list containing lists. I need each list to have a differente name and i would like to use a loop to name the list. But as the name, is a string, i cannot asign it to a value... how can I do that??
>
> global_list=[]
> for i in range (20):
>   ("list_"+i)=[]   #These would be the name of the list...
>   global_list.append("list_"+i)
>
> Thank you!!!!!


If as Chris points out you dont actually need names, a list should
suffice (with indexing serving as 'naming')
If however there are a fixed (at program-writing time) small set of
names, you can do as Dave suggests and use unpacking assignment. [Some
people like to use objects for this]
If however you need an arbitrary set of names, unknown at programming
time, a dictionary is typically what is appropriate:

For dictionary d
- get the value of name n with d[n]
- set (bind) name n to value v in dict d with d[n] = v

Which of these options you should follow is not clear from your
question; you need to tell us a bit more about what you are trying to
do.



More information about the Python-list mailing list