1

I it possible in python to create a set of lists with index i in the name?

for i in range(0,5):
    list_i = []  # here i should change according to index i

I would like to create 5 lists with names: list_0, list_1 ... _list_4 and the append something to these lists.

user3041107
  • 123
  • 2
  • 13
  • 1
    possible duplicate of [How do I do variable variables in Python?](http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python) – Morgan Thrapp Aug 07 '15 at 16:24

2 Answers2

2

Just use a dictionary of lists.

results_dict = {}
for i in range(5):
    results_dict[i] = []
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
  • ok thanks a lot, so it is only possible with dictionary ... I thought that there's another way how to create a list from a string maybe ... – user3041107 Aug 07 '15 at 16:20
  • 1
    There are some super hacky methods to use dynamic variable names, but there's no reason to use them. It's much easier/readable to just use a dictionary. – Morgan Thrapp Aug 07 '15 at 16:21
1

It might not be very straightforward, but I don't call this super hacky though. It is quite useful in some cases to use dynamic naming.

for i in range(5):
    vars()['list_%d'%i] = i

print(list_1)
print(list_2)
print(list_3)
print(list_4)

List Version

for i in range(5):
    vars()['list_%d'%i] = [i, i+1]

print(list_1)
print(list_2)
print(list_3)
print(list_4)
AmirC
  • 326
  • 5
  • 14
  • Does this work if `vars()['list_%d' %i] = []`? In other words, initializing to an empty list like the OP's question? – Engineero Aug 07 '15 at 17:08