use a loop to create lists

Dave Angel davea at davea.name
Wed Apr 10 08:36:12 EDT 2013


On 04/10/2013 04:40 AM, 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)
>
> Thank you!!!!!
>

The fact that the content of the outer list also happens to be lists is 
irrelevant to your question.  I believe the real question here is how to 
create an arbitrary bunch of new names, and bind them to elements of he 
list.

In general, you can't.  But more importantly, in general you don't want 
to.  If you come up with a convoluted way to fake it, you'll have to use 
the same convoluted way to access those names, so there's no point.  As 
Chris says, just reference them by index.

On the other hand, if the outer list happens to have exactly 7 elements, 
and you know that ahead of time, then it may well make sense to assign 
names to them.  Not list_0 through list_6, but name, addr1, ec.

global_list = []
for i in range(7):
     global_list.append[]

first_name, mid_name, last_name, addr1, addr2, city, town = global_list

Incidentally, that's approximately what a collections.namedtuple is all 
about, giving names to items that are otherwise considered elements of a 
tuple.

-- 
DaveA



More information about the Python-list mailing list