use a loop to create lists

Chris Angelico rosuav at gmail.com
Wed Apr 10 04:52:39 EDT 2013


On Wed, Apr 10, 2013 at 6:40 PM,  <martaamunar 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)

They don't need unique names. Just use the same name inside the loop:

global_list=[]
for i in range(20):
  current_list=[]  # Presumably you do something with it here
  global_list.append(current_list)

That'll work fine, and you can reference the lists by their positions
in global_list.

ChrisA



More information about the Python-list mailing list