views:

280

answers:

3

How does one generate a set of lists that incorporate the index from a for loop in the list name:

for j in range(10):
   li"j" = []

How can the index 'j' be part of the name, so the lists are li0, li1, li2, ...

Thanks!

+8  A: 

You can make li a dictionary:

li = {}
for j in range(10):
    li[j] = []
Greg Hewgill
+1  A: 

You can actually do this with exec, like so:

exec ("li%s = []" % 4)

But don't do this. You almost certainly do not want dynamically named variables. Greg Hewgill's approach will probably solve your problem.

RossFabricant
I'd vote this up for the "don't do this" part, but even showing the exec option for a case like this deserves a downvote so they cancel out...
Peter Hansen
I'd prefer `locals()["li%s" % j] = []` to the exec call. Because I'll always prefer a way that doesn't use exec or eval.
AFoglia
+1  A: 

If you do this simply to initialize lists to use them later, you should instead use one multi-dimensional list or even better tuple to do this:

li = tuple( [] for i in range( 10 ) )
li[0].append( 'foo' )
li[5].append( 'bar' )
poke
Thanks to all for the ideas. Appreciate it.
Jake
@Jake, appreciation on StackOverflow generally takes the form of "upvoting" (click above vote counts) any answers you find helpful, and eventually accepting the best one (click on its checkmark). :)
Peter Hansen