3

I'm trying to generate a series of (empty) lists using a for loop in python, and I want the name of the list to include a variable. e.g. y0, y1, y2 etc. Ideally looking something like this:

for a in range (0,16777216):
global y(a)=[]
schwal
  • 41
  • 1
  • 1
  • 3
  • 3
    You don't want to do that. See the answers for what to actually do. – Winston Ewert Aug 30 '12 at 19:00
  • 2
    Creating empty data structures you're not immediately going to use is unpythonic. Python is capable of lazy evaluation, especially in its iterative data structures. Take advantage of that! – kojiro Aug 30 '12 at 19:03
  • My final intention was to fake a table by creating a bunch of lists as the y values and the positions as the x values. Having to use another list seems a little kludgey. – schwal Aug 30 '12 at 19:10
  • 1
    @schwal: I think most Python programmers will think you've got that exactly backwards. If you use a `dict` or a list of lists, then that *is* your table-- no fakery required. In fact, the local variables you want to create would simply live in their *own* `locals()` dictionary. So under the hood you'd be using the same data structure, just far less conveniently, which doesn't make much sense. – DSM Aug 30 '12 at 19:27
  • 1
    @schwal: putting data in the names of variables is kludgey. – Ned Batchelder Aug 30 '12 at 19:36

4 Answers4

9

why wouldn't you do a dictionary of lists?

y = {}
for a in range (0,16777216):
    y[a] = []

also for brevity: https://stackoverflow.com/a/1747827/884453

y = {a : [] for a in range(0,16777216)}
Community
  • 1
  • 1
Francis Yaconiello
  • 10,829
  • 2
  • 35
  • 54
6

Not sure if this is quite what you want but couldn't you emulate the same behavior by simply creating a list of lists? So your_list[0] would correspond to y0.

Tejas Sharma
  • 3,420
  • 22
  • 35
1

The answer is: don't. Instead create a list so that you access the variables with y[0], y[1], etc. See the accepted answer here for info.

Community
  • 1
  • 1
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
1

Maybe you should check out defaultdict

form collection import defaultdict

# This will lazily create lists on demand
y = defaultdict(list)

Also if you want a constraint on the key override the default __getitem__ function like the following...

def __getitem__(self, item):
    if isintance(item, int) and 0 < item < 16777216:
         return defaultdict.__getitem__(self, item)
    else:
         raise KeyError
Doboy
  • 10,411
  • 11
  • 40
  • 48