Search code examples
pythonlistpprint

How to save parts of a list in new lists using pprint?


I try to slice a list in equally parts using Python. Because I want to reuse the output I want to create new lists out of the parts.

There are a lot of issues on stackoverflow on that. I decided to use pprint.

l = list(range(100))
n = 15
def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]
import pprint
pprint.pprint(list(chunks(list(range(0, 100)), 10)))

The actual result is as follows:

[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 ]

and so on

I expect output like

list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

and so on.

-> How can I automatically create this kind of lists? I don't want to manually number the list's name.


Solution

  • If you're only looking for a way to print the chunks, you could use a simple loop with a striding range:

    l = list(range(100))
    n = 10
    for i in range(0,len(l),n): 
        print(f"list{1+i//n} = {l[i:i+n]}")
    
    # output:
    list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
    list3 = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
    list4 = [30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
    list5 = [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
    list6 = [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
    list7 = [60, 61, 62, 63, 64, 65, 66, 67, 68, 69]
    list8 = [70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
    list9 = [80, 81, 82, 83, 84, 85, 86, 87, 88, 89]
    list10 = [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
    

    If you want actual variables (list1, list2, ...) you could use exec() in the loop but that would be rather hard to use in the rest of the program (as opposed to a list of lists):

    for i in range(0,len(l),n):
        exec(f"list{1+i//n} = l[i:i+n]")
    

    ...

    listOfLists = [ l[i:i+n] for i in range(0,len(l),n) ]
    

    ...

    listOfLists[0] is same as list1
    listOfLists[1] is same as list2 
    ...
    listOfLists[K-1] is same as listK