user1135050
user1135050

Reputation: 11

How to increment the name of a list in python

I'd like to be able to increment the name of a list so I can create multiple empty lists.

for example, I want.

List_1 = [] 
List_2 = []
...
List_x = []

I've been working with:

for j in range(5):            #set up loop
  list_ = list_ + str(j)     # increment the string list so it reads list_1, list_2, ect
  list_ = list()             # here I want to be able to have multiple empty lists with unique names
  print list_

Upvotes: 1

Views: 3807

Answers (2)

Dan Breen
Dan Breen

Reputation: 12924

I highly recommend organgeoctopus' answer, but for the sake of how to do this in Python:

# BAD HACK
for i in range(5):
    locals()['list_%d' % i] = []

Upvotes: 3

Donald Miner
Donald Miner

Reputation: 39903

The right way to do this is to have a list of lists.

list_of_lists = []
for j in range(5):
   list_of_lists.append( [] )
   print list_of_lists[j]

Then, you can access them with:

list_of_lists[2] # third empty list
list_of_lists[0] # first empty list

If you really wanted to do this, though you likely shouldn't, you could use exec:

for j in range(5):
    list_name = 'list_' + str(j)
    exec(list_name + ' = []')
    exec('print ' + list_name)

This creates the name in a string under list_name, then uses exec to execute that dynamic piece of code.

Upvotes: 15

Related Questions