Introducing itertools

In addition to the built-in functions, the itertools module contains a wealth of useful functions and generators for processing iterable streams of data.

We'll start demonstrating these functions by solving the first thousand primes problem using built-in sum() with two generator functions from itertools: islice() and count().

Earlier we made our own take() generator function for lazily retrieving the start of the sequence. We needn't have bothered, however, because islice() allows us to perform lazy slicing similar to the built-in list slicing functionality. To get the first 1000 primes we need to do something like:

from itertools import islice, count

islice(all_primes, 1000)

But how to generate all_primes? Previously, we've been using range() to create the raw sequences of integers to feed into our primality test, but ranges must always be finite, that is, bounded at both ends. What we'd like is an open ended version of range(), and that is exactly what itertools.count() provides. Using count() and islice(), our first thousand primes expression can be written out as:

>>> thousand_primes = islice((x for x in count() if is_prime(x)), 1000)

This returns a special islice object which is iterable. We can convert it to a list using the list constructor.

>>> thousand_primes
<itertools.islice object at 0x1006bae10>
>>> list(thousand_primes)
[2, 3, 5, 7, 11, 13 ... ,7877, 7879, 7883, 7901, 7907, 7919]

Answering our question about the sum of the first thousand primes is now easy, remembering to recreate the generators:

>>> sum(islice((x for x in count() if is_prime(x)), 1000))
3682913
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset