1

I need to create a list of named lists in a python script.

What I want to do is create a mklist method that will take strings in a list and create lists named for each of the strings. So, from here:

a = "area"

for i in range(1, 37):
    x = str(a) + str("%02d" % (i,))
    ' '.join(x.split())

I want to get the following:

area01 = []
area02 = []
area03 = []
area04 = []
area05 = []
area06 = []
area07 = []
area08 = []
area09 = []
area10 = []
area11 = []
area12 = []
area13 = []
area14 = []
area15 = []
area16 = []
area17 = []
area18 = []
area19 = []
area20 = []
area21 = []
area22 = []
area23 = []
area24 = []
area25 = []
area26 = []
area27 = []
area28 = []
area29 = []
area30 = []
area31 = []
area32 = []
area33 = []
area34 = []
area35 = []
area36 = []   

Any advice? I can't seem to get it. Thanks! E

eric
  • 57
  • 1
  • 8
  • What do you mean "named lists"? Are you talking about a dict? what part of it can't you "get"? Also, although redundant, your code looks like it should work to generate the names. – Marcin Aug 21 '13 at 16:03
  • Are you using Python code to generate Python code, or are you trying to create those lists within your script file? In the latter case you should probably not be doing that. – bdesham Aug 21 '13 at 16:06
  • 1
    A very similar question http://stackoverflow.com/questions/4010840/generating-variable-names-on-fly-in-python – uKolka Aug 21 '13 at 16:07
  • 5
    If you're trying to dynamically create variables, the answer is: [**Don't**](http://stackoverflow.com/a/18157868/1014938). – Zero Piraeus Aug 21 '13 at 16:08

3 Answers3

5

This calls for either a list of lists:

area = [[] for i in range(37)]

Or a dict of lists:

area = {i: [] for i in range(1, 37)}        # Python 2.7+
area = dict((i, []) for i in range(1, 37))  # Python 2.6 or earlier

Then you can access each item with:

area[1]
area[2]
...
area[36]
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

See this question.

a = "area"
for i in range(1, 37):
   x = str(a) + str("%02d" % (i,))
   locals()[x] = []

Or use globals() if you want the lists to be global.

That would give you empty list variables area01 to area36.

You should note though that just because it can be done, doesn't mean it should. A better/more readable solution would be:

area = [[] for i in range(37)]

(see John's solution)

Community
  • 1
  • 1
maged
  • 859
  • 10
  • 24
-1

Something like:

a = "area"
x = [ "%s%02d = []" % (a, i) for i in range(1,37) ]
print('\n'.join(x))

If you want your lists defined in the current Python session you sostitute the last line with

for i in range(0, 36):
    exec(x[i])

And check with

print area01
print area35

Note however that this is not advisable

Nicola Musatti
  • 17,834
  • 2
  • 46
  • 55