Search code examples
pythonlistchunks

Chunking list including overlapping intervals


Given the following list:

l1 = [0,1000,5000,10000,20000,30000,40000,50000]

I know I can create chunks of it by looking at every consecutive pair of numbers:

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))

for group in chunker(l1, 2):
   print(group)

This returns:

[0, 1000]
[5000, 10000]
[20000, 30000]
[40000, 50000]

How can I make sure that overlapping intervals, such as [1000,5000], are also included?

Expected output:

[0, 1000]
[1000, 5000] 
[5000, 10000]
[10000, 20000]
[20000, 30000]
[30000, 40000]
[40000, 50000]

Solution

  • You unnecessarily iterate over range with the step size. This way you prevent groups starting in place where the other group finishes. This code should work:

    l1 = [0,1000,5000,10000,20000,30000,40000,50000]
    
    def chunker(seq, size):
        return (seq[pos:pos + size] for pos in range(0, len(seq)))
    
    for group in chunker(l1, 2):
       print(group)
    

    The output is:

    [0, 1000]
    [1000, 5000]
    [5000, 10000]
    [10000, 20000]
    [20000, 30000]
    [30000, 40000]
    [40000, 50000]
    [50000]
    

    You may skip the last element if that is what you wish, but depends on your requirement.