How can I find the length of a filter object in python 3?
def is_valid_file(filename):
return True
full_path_fnames = filter(is_valid_file, full_path_fnames)
print(len(full_path_fnames))
You can say how much elements did it have only after you finish iterating over it. Built-in len
function calls __len__
method of an object and, as you can see, filter
objects don't have that method
>>> '__len__' in dir(filter(bool, [0, 1, 2]))
False
because they're basically iterators.
One possible way to find the length is
>>> sum(1 for _ in filter(bool, [0, 1, 2]))
2
Another one is to convert it to list
type, which of course has length:
>>> len(list(filter(bool, [0, 1, 2])))
2
Note, that all solutions will exhaust the iterator, so you won't be able to reuse it:
>>> f = filter(bool, [0, 1, 2])
>>> list(f)
[1, 2]
>>> list(f)
[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With