0

I am trying to segment python main list to sub-lists with appropriate suffix. For example, the Main List looks something like

M = [1,2,3,4,5,6]

I want to create a sub-lists like below

M_1_3 = [1,2,3]
M_4_6 = [4,5,6]

This is just for example as I do have a list of thousand elements. I tried the below 'For loop' but not working

for i in range(0,len(main_list),50):
    start = i
    end = i+50
    'sub_list_'+str(start)+'_'+str(end) = main_list[start:end]
1
  • 1
    Python indexes starts from 0, so it's adviseable to use M_0_2 and M_3_5 instead. Commented Dec 29, 2019 at 2:23

2 Answers 2

2

Python doesn't encourage dynamic variables. Use a dictionary:

sub_lists = {}
for i in range(0,len(main_list),50):
    start = i
    end = i+50
    sub_lists[str(start)+'_'+str(end)] = main_list[start:end]

And using a tuple is better than creating a string from integers:

sub_lists = {}
for i in range(0,len(main_list),50):
    start = i
    end = i+50
    sub_lists[(start, end)] = main_list[start:end]
Sign up to request clarification or add additional context in comments.

Comments

0

You can force an assignment by using exec:

main_list = list(range(200))
for i in range(0,200,50):
    start = i
    end = i+50
    exec('sub_list_'+str(start)+'_'+str(end) +'= main_list[start:end]')

print(sub_list_0_50)

However, it's not a good practice in Python.

Comments

Your Answer

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.