Exercises
Generators have a multitude of uses so you can probably start using them in your own code right away. Nevertheless, the following exercises might help you understand the features and the limitations a bit better:
- Create a generator similar to
itertools.islice()
that allows for a negative step so you can executesome_list[20:10:-1]
. - Create a class that wraps a generator so it becomes sliceable by using
itertools.islice()
internally. - Write a generator for the Fibonacci numbers.
- Write a generator that uses the sieve of Eratosthenes to generate prime numbers.
Example answers for these exercises can be found on GitHub: https://github.com/mastering-python/exercises. You are encouraged to submit your own solutions and learn about alternative solutions from others.