Send
Close Add comments:
(status displays here)
Got it! This site "robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website. Note: This appears on each machine/browser from which this site is accessed.
Python: Iterators and generators
1. Python: Iterators and generators
We have see ways to iterate over lists, sets and dictionaries using the in construct.
Here is the Python code [#1]
Here is the output of the Python code.
2. The repeat iterator
The repeat iterator can return something many times but need not take a lot of memory.
Here is the Python code [#2]
Note the use of 1_000_000 for 1000000 as Python allows the underscore to be used for grouping to make digits of numbers easier to read.
3. Files as iterators
A file in Python is a class that is an iterator.
No matter how big the file, one can read lines one by one without ever reading the entire file (unless one iterates to the end).
On the other hand, the method readall will read all the lines in the file.
Here is the output of the Python code.
4. Custom iterators
One can make a custom iterator for any collection over which it makes sense to iterate/loop.
Here is a custom iterator that returns the even numbers, in order.
Here is the Python code [#3]
Here is the output of the Python code.
5. Termination
If we try something like the following, the loop will never end.
for i1 in evens1():
# do something with i1
# end for
Iterators do not work well when the underlying sequences do not end. Instead, a generator may be more appropriate.
6. Generators
A generator function in Python is a function that contains one or more yield statements.
Here is the Python code [#4]
Here is the output of the Python code.
7. Generator expressions
A generator expression can be created as needed as an expression rather than using a named function.
A similar concept is a lambda function which is a way to make a function as an expression rather than using a named function.
Here is the Python code [#5]
Here is the output of the Python code.
8. End of page