# Python3's filter with lambda function and generator

Please, consider this Python 3 code to generate prime numbers using an unbounded sieve of eratosthenes:

import itertools def primes(): numbers = itertools.count(2) while True: prime = next(numbers) yield prime numbers = filter(prime.__rmod__,numbers) prime_gen = primes() next(prime_gen) # Prints 2 next(prime_gen) # Prints 3 next(prime_gen) # Prints 5 next(prime_gen) # Prints 7

So far so good. Now, let's replace the prime.__rmod__ function with a lambda that does the same thing:

import itertools def primes(): numbers = itertools.count(2) while True: prime = next(numbers) yield prime numbers = filter(lambda n: n % prime,numbers) prime_gen = primes() next(prime_gen) # Prints 2 next(prime_gen) # Prints 3 next(prime_gen) # Prints 4 next(prime_gen) # Prints 5

**Why the lambda function is not working with the filter?** There is something going on with the scope of the lambda function?

## Answers

As R Nar comments this is due to the scope of the lambda function. Because prime is global to the lambda function the same value for prime is used in every lambda when filter tries to do its job. The solution is creating a closure for each lambda in order to make them remember the value of prime when they are created:

filter(lambda n, prime=prime: n % prime,numbers)