user12616816
user12616816

Reputation: 9

Create subsets from Python list with suffix

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]

Upvotes: 0

Views: 150

Answers (2)

Anonymous
Anonymous

Reputation: 12017

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]

Upvotes: 2

mathfux
mathfux

Reputation: 5939

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.

Upvotes: 0

Related Questions