What is the most “pythonic” way to iterate over a list in chunks?

What is the most “pythonic” way to iterate over a list in chunks?

Asked on November 4, 2018 in Python.
Add Comment


  • 3 Answer(s)

    Python’s itertools docs:

    from itertools import izip_longest
     
    def grouper(iterable, n, fillvalue=None):
        args = [iter(iterable)] * n
        return izip_longest(*args, fillvalue=fillvalue)
    

    Example

    In pseudocode to keep the instance terse the following is used.

    grouper('ABCDEFG', 3, 'x') --> 'ABC' 'DEF' 'Gxx'
    

     

     

    Answered on November 4, 2018.
    Add Comment

    Try the following method:

    def chunker(seq, size):
        return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
    

    Simple. Easy. Fast. Works with any sequence in python:

    text = "I am a very, very helpful text"
     
    for group in chunker(text, 7):
        print repr(group),
    # 'I am a ' 'very, v' 'ery hel' 'pful te' 'xt'
     
    print '|'.join(chunker(text, 10))
    # I am a ver|y, very he|lpful text
     
    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']
    
    Answered on November 4, 2018.
    Add Comment

    This could be done by following code:

    chunkSize= 4
    for i in xrange(0, len(ints), chunkSize):
        chunk = ints[i:i+chunkSize]
        # process chunk of size <= chunkSize
    
    Answered on November 4, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.