Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically declare/create lists in python [closed]

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

like image 985
Cheese Avatar asked Aug 07 '13 08:08

Cheese


People also ask

How do you automatically create a list in Python?

Use List Comprehension & range() to create a list of lists. Using Python's range() function, we can generate a sequence of numbers from 0 to n-1 and for each element in the sequence create & append a sub-list to the main list using List Comprehension i.e. It proves that all sub lists have different Identities.

Does Python have dynamic list?

And lists are also dynamic, meaning that you can add elements to the list or remove elements from a list completely. So the list can grow or shrink depending on how you use it.


2 Answers

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
[[], [], [], []]
like image 76
falsetru Avatar answered Sep 17 '22 16:09

falsetru


You can not achieve this in Python. The way recommended is to use a list to store the four list you want:

>>> depth = [[]]*4
>>> depth
[[], [], [], []]

Or use tricks like globals and locals. But don't do that. This is not a good choice:

>>> for i in range(4):
...     globals()['depth_{}'.format(i)] = []
>>> depth_1
[]
like image 40
zhangyangyu Avatar answered Sep 19 '22 16:09

zhangyangyu