cypher
cypher

Reputation: 449

Why does the list inside the loop become empty after filtering

I am trying lambda functions in python 3. I tried the example (to find prime number) given here in this link: http://www.secnetix.de/olli/Python/lambda_functions.hawk This did not work in python 3.

I am trying to assign the same global variable after filtering. unable to make it work.

The variable primes becomes empty array after the first loop. Does anyone have any idea ?

def test1():
    num = 50
    primes = range(2,num); 
    for i in range(2, 8): 

        print(list(primes)); 
        primes = filter(lambda x: x % i, primes); 
        print(list(primes), i); 

    print("last"); 
    print(list(primes)); 

test1(); 

Upvotes: 1

Views: 960

Answers (1)

jpp
jpp

Reputation: 164693

filter returns an iterator. Once the iterator is exhausted, as it is by list in your code, you cannot reuse it.

The reason this would work in Python 2.x is because filter returned a list in earlier versions.

Below is a minimal example of this behaviour in Python 3.

odds = filter(lambda x: x % 2, range(10))

res = list(odds)
print(res)
# [1, 3, 5, 7, 9]

res = list(odds)
print(res)
# []

To get round this, assign a list to primes instead of an iterator:

primes = list(filter(lambda x: x % i, primes))

Upvotes: 1

Related Questions