Elaheh Hashemi
Elaheh Hashemi

Reputation: 1

Operation of Filter Methode

why is the answer a empty List with list command?

myList = [12,15,10,16,20]
even_numbers = lambda value: value%2==0
repo = filter(even_numbers,myList)
for x in repo:
    print(x)
list(repo)

I want to clear the problem in my code

Upvotes: 0

Views: 33

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54698

Because filter returns a generator, not a list. The for loop consumes everything in the generator, leaving it empty. If you need to reuse the contents, convert it to a list:

repo = list(filter(even_numbers,myList))

or use a comprehension:

repo = [e for e in myList if even_numbers(e)]

Upvotes: 1

Related Questions