Python Split List Into Pair or Chunks

Aug 8, 2019
items = [1, 2, 3, 4, 5, 6]chunk_size = 2chunks = ...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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.