In previous articles I’ve wrote about how to create an iterator in Python by implementing iterator protocolor using the yield keyword. In this article I’ll describe generators: a piece of Python syntax that can turn many iterators into one-liners.
While you can write iterators in Python by implementing iterator protocol it usually requires a lot of code and looks cumbersome. To facilitate this task Python provides a powerful syntax to create iterators. By using these constructions we can write complex iterators using just few lines of code.
Iterator is a powerful pattern that was recognised at least as early as 1994 and since then it was incorporated in syntax of almost every modern programming language.
Python also implements this pattern providing a pithy and concise syntax to iterate over lists, maps, dictionaries and other data structures:
for i in [1, 2, 3, 4]: print i
In this article I will write about how an iterator is used in Python, how to implement your own iterator and what types of iterators exist in Python.