A generator works by "saving" where it last left off (or yielding) and giving the calling function a value.
A generator function requires Python's yield statement
To create a generator in #Python, you must use the `yield` keyword.
Here's an example that can generate an infinite number of return values:
You can also make a generator that only generates a finite number of items.
For this example, you use the `yield` keyword 3 times:
You can also loop over a generator object. This allows you to work on the items that the generator yields to you one at a time without the need to call `next()`
Python has generators built into the language. For example, if you open a file, you can iterate over that file object line-by-line.
Under the covers, Python is yielding those lines one at a time. In other words, it's using a generator!
You can read more about generators in my tutorial @mousevspython
Iterators in #Python are usually defined as needing the following two methods:
๐ __iter__ - provides iteration support
๐ __next__ - returns the next item in the container
๐งต๐๐
A #Python list isn't considered an iterator. It is an iterable, something that you iterate over. But because lists don't define `__next__`, they aren't technically an iterator.
However, you can turn a list into an iterator using the built-in `iter()` function:
You can create your own iterators in #Python by adding the appropriate magic methods to your class.