Iterators
-
Generator Expressions
We’ve seen list, set and dictionary comprehensions but we haven’t seen tuple comprehensions. That’s because there aren’t any tuple comprehensions in Python. The syntax that you might think would create one, actually creates an iterator. This is known as a generator expression. This code prints some square numbers.
-
Yield: Creating Generator Functions
An easier way to create an iterator in Python (easier than implementing __next__ and __iter__) is to use the yield keyword to create a generator function. Although yield may at first seem counter-intuitive, it really behaves a lot like the return keyword. The difference is, you can iterate over the yielded values. In this code…
-
Creating an Iterator
Iterators in Python are objects that you can retrieve other objects from, one by one. For example, you can loop over them using for … in. To turn a class into an iterator, you have to implement the __iter__ and __next__ dunder methods. To stop iteration you raise StopIteration. Iterator Example