Is the function filter deprecated?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Apr 7 03:06:06 CEST 2011


On Wed, 06 Apr 2011 19:20:31 -0400, Jabba Laci wrote:

> Hi,
> 
> I tried Pylint today and it gave me a warning for the function "filter".
> Is it deprecated? 

No.


> Is the usage of list comprehensions encouraged? 

Certainly, but list comprehensions are not necessarily equivalent to 
filter. In Python 3, filter is lazy and is closer to generator 
expressions than list comprehensions. In Python 2, filter is equivalent 
to a list comp.


> The
> transformation is not complicated, by the way: replace "filter( func,
> seq )" with "[ x for x in seq if func(x) ]" .

Provided func is not None, in which case you need:

filter(None, seq) -> [x for x in seq if x]

There's no doubt in my mind that list comps are more general than filter, 
and therefore more powerful, but for simple filters, I like filter().

I think filter would be more useful if it took an arbitrary number of 
iterable arguments rather than just a single. The equivalent of:


filter(func, *seqs) -> [x for x in itertools.chain(*seqs) if func(x)]


although I suppose functional programming purists might object :)



-- 
Steven



More information about the Python-list mailing list