Itertools in Python 3, By Example – Real Python
Some Interesting Things Include:
itercreates an iterator that spits out one element from an iterable at a time. Effectively, it’s a pointer to the next element to be yielded- Elements created by iterators are tuples
- Having multiple
iters allows one to return “batches” of items:
import itertools as it
def batch(iterable, batch_size):
iters = [iter(iterable)] * batch_size
return zip(*iters)- The above won’t work if
len(iterable)is a non-integer multiple ofbatch_size. To fix that, one can useit.zip_longest:
def batch_proper(iterable, batch_size, fillvalue):
iters = [iter(iterable)] * batch_size
return it.zip_longest(*iters, fillvalue)it.countis kinda likerangeexcept it always returns an infinite sequence- Similarly,
it.islicedoes slicing but on potentially infinite iterators it.accumulateaccumulates values in an iterable, kinda like howreduceworks.- The default
funcargument forit.accumulateisoperator.add
- The default
it.teecreatesn“entangled” iterators, each with its own FIFO queue.- When any of the iterator pulls new values from
it.tee, those new values are appended to all the other iterator queues created byit.teeas well - Is more memory-inefficient if one iterator keeps pulling data
- When any of the iterator pulls new values from