1

I stumble upon some issue with list. I have nested list like this one [[1, 2, 3], [4, 5, 6],[7, 8, 9]]

This list can be arbitrarily large and inner list does not need to be in the same length(size). What I would like to achieve is to take out each inner list and assign to new variable. This means in our toy example the following.

Var1=[1,2,3]
Var2=[4,5,6]
Var3=[7,8,9]

I can index it manually in toy example each inner list, but this not desired result. I need to store as separate variable each inner list. Moreover I prefer function to do this for me.

What I need is a function that takes nested list and assigns each inner list to variable automatically. Input of function should be nested list and output should be each inner list assign to variable. The solution should scale to larger list size.

vasiop
  • 89
  • 1
  • 6
  • 2
    is there a reason you want to do this? what makes indexing the original list a problem? – python_user Jan 31 '21 at 12:33
  • I need to be automatic. I do not want do it manually. – vasiop Jan 31 '21 at 12:34
  • ok, can you edit the question saying how assigning to different variables would make your problem easier? as it stands you have not pointed out why indexing is not an optimal approach for you – python_user Jan 31 '21 at 12:36
  • @ python_user Done it. – vasiop Jan 31 '21 at 12:39
  • You can use a dictionary to solve your problem. Maintain a counter for key and loop through the nested list. That way it will be automatic too. – neilharia7 Jan 31 '21 at 12:43
  • @python_user It is bad because imagine that I have longer list with numerous entries. E.g. let's say 100 inner list. I need to every time to refer to index. – vasiop Jan 31 '21 at 12:48
  • Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – buran Jan 31 '21 at 12:54

1 Answers1

1

This should work:

main_list = [[1, 2, 3], [4, 5, 6],[7, 8, 9]]
for i in range(len(main_list)):
    declare_statement = f'Var{i} = {main_list[i]}'
    exec(declare_statement)

'''
now each value of the main_list is stored in variable different variable with
prefix "Var" and index of that value as postfix 
'''

That means print(Var0) would display [1, 2, 3], print(Var1) would display [4, 5, 6] and so on but honestly I don't see a point to this. You could've achieved the same thing by print(main_list[0]) and print(main_list[1]) it is just a waste of memory to assign each value of a list to a variable and it also defeats the purpose of lists and arrays.

baisbdhfug
  • 548
  • 1
  • 4
  • 14