Search code examples
pythonlistpython-itertoolscyclenested-lists

Cyclically pop the contents of one list into a list of lists


I have a list

main_list = [1,2,3,4,5,6,7,8,9,10,11,12]

and I want to split the lists into multiple lists and I want the output as shown below-

list1 = [1,9]    
list2 = [2,10]    
list3 = [3,11]    
list4 = [4,12]    
list5 = [5]    
list6 = [6]    
list7 = [7]
list8 = [8]

Solution

  • Here is a simple code:

    main_list = [1,2,3,4,5,6,7,8,9,10,11,12]
    
    list_count = 8
    lists = [[] for _ in range(list_count)]
    
    for count, item in enumerate(main_list):
        lists[count % list_count].append(item)
    
    print(lists)
    

    Output:

    [[1, 9], [2, 10], [3, 11], [4, 12], [5], [6], [7], [8]]
    

    EDIT

    If

    main_list = [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2)]
    

    then output

    [[(1, 1), (3, 1)], [(1, 2), (3, 2)], [(1, 3)], [(1, 4)], [(2, 1)], [(2, 2)], [(2, 3)], [(2, 4)]]