Python Iterate over a List in Chunks

Posted on July 31, 2019 at 3:16 pm

Here is a function that iterates a list in chunks:

# (in python 2 use xrange() instead of range() to avoid allocating a list)
def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))

And here is how to use it:

animals = ['cat', 'dog', 'rabbit', 'duck', 'bird', 'cow', 'gnu', 'fish']
 
for group in chunker(animals, 3):
    print group
 
# ['cat', 'dog', 'rabbit']
# ['duck', 'bird', 'cow']
# ['gnu', 'fish']

Reference:

https://stackoverflow.com/a/434328

Receive updates via email

Other Posts

Updated Posts