list object created by map,filter returns empty list

Question:

from functools import reduce
>>> numbers = [1,2,3,4,5,6]
>>> odd_numbers = filter(lambda n: n % 2 == 1, numbers)
>>> squared_odd_numbers = map(lambda n: n * n, odd_numbers)
>>> total = reduce(lambda acc, n: acc + n, squared_odd_numbers)

if I want to check the contents of odd_numbers, I run

list(odd_numbers)

However, this returns an empty list []. This is python 3.6+

If I run list(odd_numbers) right after run the filter function. I got the list element

>>> numbers = [1,2,3,4,5,6]
>>> odd_numbers = filter(lambda n: n % 2 == 1, numbers)
>>> list(odd_numbers)
[1, 3, 5]

Why this happens?

Asked By: tudou

||

Answers:

The returned object from filter works like an iterator; you can only iterate over it once:

>>> x=[1,2,3,4,5,6]
>>> odds=filter(lambda n: n%2 == 1, x)
>>> list(odds)
[1, 3, 5]
>>> list(odds)
[]

It’s “used up” after the first time you loop over it (which happens in the map() line).

Same is true of the map object.

Answered By: RemcoGerlich
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.