Python Split List Into Pair or Chunks

August 8, 2019
items = [1, 2, 3, 4, 5, 6]
chunk_size = 2

chunks = ...

for item in chunks:
    print(item[0], item[1])
1 2
3 4
5 6

Solution 1

chunks = zip(*[iter(items)]*chunk_size)

Solution 2

def chunk(items, chunk_size):
    for i in range(0, len(items), chunk_size):
        yield items[i:i + chunk_size]

chunks = chunk(items, chunk_size)

or

chunks = [items[i:i + chunk_size] for i in range(0, len(items), chunk_size)]

Solution 3

If you don’t actually need to split but to access them in chunks.

for i in range(0, len(items), chunk_size):
    print(items[i], items[i+1])

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.