...

/

Simplifying Code through Iterators

Simplifying Code through Iterators

Learn how to improve code through repeated iterations and nested loops.

We'll cover the following...

Now, let's briefly discuss some situations that can be improved with the help of iterators and occasionally the itertools module. After discussing each case, and its proposed optimization, we'll close each point with a corollary.

Repeated iterations

Now that we have seen more about iterators and introduced the itertools module, we can show you how one of the first examples of this chapter (the one for computing statistics about some purchases) can be dramatically simplified:

Press + to interact
import logging
from itertools import tee
from statistics import median
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def produce_values(how_many):
for i in range(1, how_many + 1):
logger.debug("producing purchase %i", i)
yield i
def process_purchases(purchases):
min_, max_, avg = tee(purchases, 3)
return min(min_), max(max_), median(avg)
def main():
data = produce_values(7)
obtained = process_purchases(data)
logger.info("Obtained: %s", obtained)
assert obtained == (1, 7, 4)
if __name__ == "__main__":
main()

In this example, itertools.tee will split the original iterable into three new ones. We will use each of these for the different kinds of iterations that we require, without needing to repeat three different loops over purchases. ...