Filtering comprehensions

All three types of collection comprehension support an optional filtering clause which allows us to choose which items of the source are evaluated by the expression on the left. The filtering clause is specified by adding if <boolean expression> after the sequence definition of the comprehension, If the boolean expression returns false for an item in the input sequence, then no value is evaluated for that item in the result.

To make this interesting, we'll first define a function that determines if its input is a prime number:

>>> from math import sqrt
>>> def is_prime(x):
... if x < 2:
... return False
... for i in range(2, int(sqrt(x)) + 1):
... if x % i == 0:
... return False
... return True
...

We can now use this in the filtering clause of a list comprehension to produce all primes less than 100:

>>> [x for x in range(101) if is_prime(x)]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
..................Content has been hidden....................

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