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.

asked Jan 31, 2021 at 12:29
7
  • 2
    is there a reason you want to do this? what makes indexing the original list a problem? Commented Jan 31, 2021 at 12:33
  • I need to be automatic. I do not want do it manually. Commented Jan 31, 2021 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 Commented Jan 31, 2021 at 12:36
  • @ python_user Done it. Commented Jan 31, 2021 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. Commented Jan 31, 2021 at 12:43

1 Answer 1

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.

answered Jan 31, 2021 at 12:48
1
  • Thanks. This is what I look for. Commented Jan 31, 2021 at 12:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.