0

Can I create multiple lists using loop? What I want to achieve is create several lists For eg:

lt_1 = []
lt_2 = []
lt_3 = []
......

and later add items in each list separately. I tried naming every list as above but with 20 lists named separately, it didn't look nice. So I tried using for loop but with no success. The solution given here suggested using dictionary but then I couldn't append items in each list. Also I actually want to create separate list (if possible) so I can work with each element within each list.

I tried the following way (which obviously won't work) but what I want to do is pass the 'z' in lt_z as the looping variable and not variable name (Hope this makes sense)

for z in range(0,20):
    lt_z = []

P.S. I am just beginning to learn python so I might have missed something while trying the solution with dictionary.

HoppyHOP
  • 19
  • 3

2 Answers2

1

Most pythonic would probably still be using a dict:

listDict = {}
for i in range(10):
    listDict[f'lt_{i}'] = []

Then you can use it like this like individual lists:

>>> print(listDict)
{'lt_0': [], 'lt_1': [], 'lt_2': [], 
 'lt_3': [], 'lt_4': [], 'lt_5': [], 
 'lt_6': [], 'lt_7': [], 'lt_8': [], 
 'lt_9': []}

>>> listDict['lt_2'].append(5)
>>> listDict['lt_2'].append(6)
>>> print(listDict['lt_2'])
[5, 6]

Dynamically creating variable names is in principle possible, but almost always a very bad idea.

Update

You asked about how f'lt_{i}' works. This is just a so called f-string. It is equivalent to 'lt_'+str(i) wich concatenates the lg_ with the current value of i. See e.g. here for more information on how to use f-strings.

user_na
  • 2,154
  • 1
  • 16
  • 36
1

You can either use lists of lists i.e. nested list, or you can use a dictionary with values as list.

If you want to modify the values later based on name, using dictionary with values as list will be helpful, if the name doesn't matter and you just want to do modification based on the position/index, then you can use nested list. But I think the better approach is to use nested list rather than dictionary, here is a code snippet:

result = []
for z in range(0,20):
    lt_z = []
    result.append(lt_z)
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45