dynamically declare/create lists in python

Cheese picture Cheese · Aug 7, 2013 · Viewed 40.6k times · Source

I am a beginner in python and met with a requirement to declare/create some lists dynamically for in python script. I need something like to create 4 list objects like depth_1,depth_2,depth_3,depth_4 on giving an input of 4.Like

for (i = 1; i <= depth; i++)
{
    ArrayList depth_i = new ArrayList();  //or as depth_i=[] in python
}

so that it should dynamically create lists.Can you please provide me a solution to this?

Thanking You in anticipation

Answer

falsetru picture falsetru · Aug 7, 2013

You can do what you want using globals() or locals().

>>> g = globals()
>>> for i in range(1, 5):
...     g['depth_{0}'.format(i)] = []
... 
>>> depth_1
[]
>>> depth_2
[]
>>> depth_3
[]
>>> depth_4
[]
>>> depth_5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'depth_5' is not defined

Why don't you use list of list?

>>> depths = [[] for i in range(4)]
>>> depths
[[], [], [], []]