Reputation: 21
I executed the following:
filter(lambda x: x%2 , range(10))
sum(filter(lambda x: x%2 , range(10)))
abc = filter(lambda x: x%2 , range(10))
sum(abc) # => 25
sum(abc) # => 0
Why?
Upvotes: 2
Views: 46
Reputation: 239693
I think you are using Python 3.x. In Python 3.x, filter
returns an iterable, not a list.
So, once you iterate the filter
with the sum
the first time, the filter
iterable is exhausted. Next time, when you do the same, filter
is already exhausted (it has no more elements). That is why you are getting the default return value 0.
You can confirm the same, like this
>>> abc = filter(lambda x: x%2 , range(10))
>>> list(abc)
[1, 3, 5, 7, 9]
>>> list(abc)
[]
Upvotes: 2