Reputation: 283
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!
Upvotes: 2
Views: 8865
Reputation: 387557
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' )
Upvotes: 3
Reputation: 12492
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.
Upvotes: 0
Reputation: 992807
You can make li
a dictionary:
li = {}
for j in range(10):
li[j] = []
Upvotes: 11