An iterator is a nice concept since it allows to create laze sequences, i.e., sequences that have elements that are computed only when they are requested by retrieving the enxt element.
Python allows for two basic ways to implement iterators, either as
function that have a LHS yield statements, or as class that implement
an __iter__ and a next method.
However, often it is not necessary to implements iterators from scratch,
often they can be constructed by using the Python standard library's
itertools functionality.
accumulator.py: illustrates the use ofitertools'saccumulatein for various types of data and operators.count_down.py: simple illustration of a class that implements an iterable.event_generate.py: a sequence ofEventobjects is generated by an instance of theEventIterclass. Events have a type, a start time, and a duration. Events of the same type can not overlap. TheEventIterconstructor takes a list of event types, and a start time. It generates sequence of random type, start time and duration, until an event is generated that last later than the stop time.generators.ipynb: Jupyter notebook illustrating generators.people.py: illustration ofitertools'sgroupby, andoperator'sattrgettermethods. Note thatgroupbydoes not reorder the original iterators element, but only groups consecutive elements that have the same key.primes.py: this script will generate the sequence of prime numbers until it is interupted. The iterator is implemented by a function with ayieldstatement.primes_multiple_calls.py: illustrates that a function withyieldinstantiates a generator when called, and hence "starts over" for eachfor-loop.primes_itertools.py: this script also generates a potentially infinite sequence of prime numbers, but it is implemented using thecountfunction of theitertoolsmodule in Python's standard library, as well as thefilterfunction.dataset.py: illustrates the__iter__and__next__methods, as well as utilities of theoperatormodule.generating_data.py: a retake of the data geenration script in Fundamentals, now usingitertoolsand built-in Python functional features.iterators_vs_generators.ipynb: comparing iterators to generators.