Search code examples
pythonlistindices

How can I obtain the elements in a single list with specified indices?


Suppose I have a list

li = ['a0','b0','c0','a1','b1','c1',...,'an','bn','cn']

I want to obtain

['a0',...,'an'], ['b0',...,'bn'], ['c0',...,'cn']

using a for loop. I'm trying to do something like

for i in range(3): # for a,b,c
    lis = [li[i][k] for i in range(n+1)] # Hope to get [a0,...,an], etc
    print(lis)

However, this method won't work because there's no sublist here. I don't think I can do something like i*k because the indices start at 0. How can I obtain the desired output?


Solution

  • You can just create different slices:

    count = 3 
    main_list = ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'an', 'bn', 'cn']
    
    for i in range(count):
        sub_list = main_list[i::count]
        
        print(sub_list)
    

    Or use a list comprehension if you want to create a list of sublists:

    count = 3
    main_list = ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'an', 'bn', 'cn']
    sub_lists = [main_list[i::count] for i in range(count)]
    
    print(sub_lists)