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?
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?
Your question is a bit vague, but check out the
grouper
recipe in theitertools
documentation.(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 theitertools
module.)Here's another approach that works on older version of Python that don't have izip_longest:
No filler, so the last group might have fewer than n elements.