Partition a list

def partition(lst, partition_size):
    if partition_size < 1:
        partition_size = 1
    return [
        lst[i:i + partition_size]
        for i in range(0, len(lst), partition_size)
    ]

Examples

a = [1] * 10
print(a)
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b = partition(a, 2)
print(b)
[[1, 1],[1, 1],[1, 1],[1, 1],[1, 1]]
c = partition(a, 4)
print(c)
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1]]
d = partition(a, 1)
print(d)
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
e = partition(a, 0)
print(e)
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]

About this Entry


Comments