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)=[]
5
  • 3
    You don't want to do that. See the answers for what to actually do. Commented Aug 30, 2012 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! Commented Aug 30, 2012 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. Commented Aug 30, 2012 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. Commented Aug 30, 2012 at 19:27
  • 1
    @schwal: putting data in the names of variables is kludgey. Commented Aug 30, 2012 at 19:36

4 Answers 4

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)}
Sign up to request clarification or add additional context in comments.

3 Comments

Except all the keys are integers, so perhaps a list of lists or sparse array?
i typo'd that a, it wasn't supposed to be a string. fixed.
added dict comprehension
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.

Comments

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.

1 Comment

You should mark this question as a duplicate to the one you linked.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.