Search code examples
pythonpython-3.xlistchunks

Slice list in python


I need to slice a list using python 3.7, and slice should contains two elements, if at the end we got one elements (like below), that's last element should go to previous part.

def solution(A):
    l = len(A)
    size = 2
    for i in range(1, len(A), size):
        print(A[i:i+2])

solution([4,2,2,5,1,5,8,9])  

Output:

[2, 2]
[5, 1]
[5, 8]
[9]

Desire output:

[2, 2]
[5, 1]
[5, 8, 9]

Thanks for your help


Solution

  • def solution(A):
        l = len(A)
        size = 2
        groups = [ A[i:i+size] for i in range(1, len(A), size) ]
        if len(groups[-1]) < size:
           groups[-2].extend(groups.pop())
        for x in groups:
            print(x)
    

    Works for every value of size, not just 2.