Skip to content

Latest commit

 

History

History

README.md

Iterators

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.

What is it?

  1. accumulator.py: illustrates the use of itertools's accumulate in for various types of data and operators.
  2. count_down.py: simple illustration of a class that implements an iterable.
  3. event_generate.py: a sequence of Event objects is generated by an instance of the EventIter class. Events have a type, a start time, and a duration. Events of the same type can not overlap. The EventIter constructor 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.
  4. generators.ipynb: Jupyter notebook illustrating generators.
  5. people.py: illustration of itertools's groupby, and operator's attrgetter methods. Note that groupby does not reorder the original iterators element, but only groups consecutive elements that have the same key.
  6. primes.py: this script will generate the sequence of prime numbers until it is interupted. The iterator is implemented by a function with a yield statement.
  7. primes_multiple_calls.py: illustrates that a function with yield instantiates a generator when called, and hence "starts over" for each for-loop.
  8. primes_itertools.py: this script also generates a potentially infinite sequence of prime numbers, but it is implemented using the count function of the itertools module in Python's standard library, as well as the filter function.
  9. dataset.py: illustrates the __iter__ and __next__ methods, as well as utilities of the operator module.
  10. generating_data.py: a retake of the data geenration script in Fundamentals, now using itertools and built-in Python functional features.
  11. iterators_vs_generators.ipynb: comparing iterators to generators.