2

I want to split a given python list into chunks, similar to the following link, but in reverse.

How do you split a list into evenly sized chunks in Python?

Currently forward_chunk([1,2,3],2) = [[1,2], [3]]

However I want backward_chunk([1,2,3],2) = [[1], [2,3]]

# what I currently have
def forward_chunk(list, size):
    for i in range(0, len(list), size):
        yield list[i:i+size]

I cannot for the life of me make all the ranges and list slices work in order to achieve the backward dream. Anyone have any ideas?

Community
  • 1
  • 1
AlanSTACK
  • 4,735
  • 3
  • 33
  • 80

3 Answers3

3

Sth. like this maybe:

def backward_chunk(l, size):
    start = 0
    for end in range(len(l)%size, len(l)+1, size):
        yield l[start:end]
        start = end

> list(backward_chunk([1, 2, 3], 2))
[[1], [2, 3]]

The first chunk size is calculated as the modulo of list length and general chunk size. And please, don't call variables list.

user2390182
  • 67,685
  • 6
  • 55
  • 77
2

Find how many extra elements there will be, split the list in two, yield the first piece, then do the chunk operation and yield the rest.

def forward_chunk(lst, size):
    piece = len(lst) % size
    piece, lst = lst[:piece], lst[piece:]
    yield piece
    for i in range(0, len(lst), size):
        yield lst[i:i+size]
TigerhawkT3
  • 46,954
  • 6
  • 53
  • 87
0

You can use a normal chunk generator and reverse the list if you want.

def chunk(data, size, reverse=False):
    data = data[::-1] if reverse else data
    for n in range(0, len(data), size):
        yield data[n:n+size]

Example usage:

info = [1, 2, 3, 4, 5, 6, 7, 8]
for i in chunk(info, 4):
    print(i)  # => [1, 2, 3, 4], [5, 6, 7, 8]
for i in chunk(info, 4, True):
    print(i)  # => [8, 7, 6, 5], [4, 3, 2, 1]

If you want to only reverse the ORDER and not the list itself, just yield data[n:n+size][::-1] if reverse is True.

Goodies
  • 3,882
  • 3
  • 25
  • 50