Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yield multiple objects at a time from an iterable object?

How can I yield multiple items at a time from an iterable object?

For example, with a sequence of arbitrary length, how can I iterate through the items in the sequence, in groups of X consecutive items per iteration?

like image 354
Matt Joiner Avatar asked Jan 22 '23 15:01

Matt Joiner


1 Answers

Your question is a bit vague, but check out the grouper recipe in the itertools documentation.

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

(Zipping the same iterator several times with [iter(iterable)]*n is an old trick, but encapsulating it in this function avoids confusing code, and it is the same exact form and interface many people will use. It's a somewhat common need and it's a bit of a shame it isn't actually in the itertools module.)

like image 71
Mike Graham Avatar answered Jan 25 '23 05:01

Mike Graham