Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the length of a filter object in python 3

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))
like image 674
ensnare Avatar asked Dec 07 '22 01:12

ensnare


1 Answers

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) 
[]
like image 191
vaultah Avatar answered Dec 08 '22 16:12

vaultah