Itertools in Python 3, By Example – Real Python
Some Interesting Things Include:
iter
creates 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
iter
s allows one to return “batches” of items:
- The above won’t work if
len(iterable)
is a non-integer multiple ofbatch_size
. To fix that, one can useit.zip_longest
:
it.count
is kinda likerange
except it always returns an infinite sequence- Similarly,
it.islice
does slicing but on potentially infinite iterators it.accumulate
accumulates values in an iterable, kinda like howreduce
works.- The default
func
argument forit.accumulate
isoperator.add
- The default
it.tee
createsn
“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.tee
as well - Is more memory-inefficient if one iterator keeps pulling data
- When any of the iterator pulls new values from