I'm trying to understand how filter()
function works in Python. Namely, Python 3. I know about list comprehensions, and they work as they should in my example, I just want to understand how filter()
function works.
Suppose I have a list of integers I'd like to filter once, and then filter one more time:
myList = [1, 2, 3, 4, 5]
myList = filter(lambda i: i <= 3, myList)
myList2 = filter(lambda i: i == 1, myList)
print(list(myList))
print(list(myList2))
The output is:
[1, 2, 3]
[]
Why myList2
is empty? I know that filter()
function returns a filter
object, but isn't it iterable and allowed for use in subsequent filter()
call?
If I change the code to
myList = [1, 2, 3, 4, 5]
myList = filter(lambda i: i <= 3, myList)
myList2 = filter(lambda i: i == 1, list(myList))
print(list(myList))
print(list(myList2))
the output is:
[]
[1]
Why myList
became empty after converting it to list explicitly in the 2nd filter
call?