Dynamic variables are considered a really bad practice. Hence, I won't be giving a solution that uses them. :)
As @GarrettLinux pointed out, you can easily make a list comprehension that will create a list of lists. You can then access those lists through indexing (i.e. lst[0]
, lst[1]
, etc.)
However, if you want those lists to be named (i.e. var1
, var2
, etc.), which is what I think you were going for, then you can use a defaultdict from collections.defaultdict
:
from collections import defaultdict
dct = defaultdict(list)
for i in xrange(5):
dct["var{}".format(i+1)]
Demo:
>>> dct
defaultdict(<type 'list'>, {'var5': [], 'var4': [], 'var1': [], 'var3': [], 'var2': []})
>>> dct["var1"]
[]
>>> dct["var1"].append('value')
>>> dct["var1"]
['value']
>>> dct
defaultdict(<type 'list'>, {'var5': [], 'var4': [], 'var1': ['value'], 'var3': [], 'var2': []})
>>>
As you can see, this solution closely mimics the effect of dynamic variables.