Is the function filter deprecated?

J

Jabba Laci

Hi,

I tried Pylint today and it gave me a warning for the function
"filter". Is it deprecated? Is the usage of list comprehensions
encouraged? The transformation is not complicated, by the way:
replace "filter( func, seq )" with "[ x for x in seq if func(x) ]" .

Thanks,

Laszlo
 
S

Steven D'Aprano

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 :)
 
P

Paul Rubin

Steven D'Aprano said:
filter(func, *seqs) -> [x for x in itertools.chain(*seqs) if func(x)]
although I suppose functional programming purists might object :)

Maybe you really want

filter(func, chain.from_iterable(seqs))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top