[Python-ideas] Allow filter(items)

Steven D'Aprano steve at pearwood.info
Wed Aug 7 09:08:12 CEST 2013


On Tue, Aug 06, 2013 at 07:46:36PM -0700, Shane Green wrote:
> It seems kind of like there should be a filtered operation like there is a sorted one.

In Python 2, that is spelled filter(predicate, values).

In Python 3, filter returns a lazy iterator rather than an eager list, 
so you can write list(filter(predicate, values)) instead.

> (and why not have a list.filter(predicate=None) to perform in place filtering for that matter?)

Because it's not 1972, we have more than 64K of memory, and most 
in-place operations should be re-written to return a new list instead 
:-)

That's a glib answer, of course, but in general making an external 
filtered copy, then writing back into the list, will be faster than 
modifying the list in place:

values[:] = filter(predicate, values)


It's also more flexible. Here is how to filter only the last 100 items:

values[-100:] = filter(predicate, values[-100:])

The filter function itself doesn't need to know where the data is coming 
from or where it is going.

Another reason is, filter being a method implies that all sequences (or 
at least, all list-like sequences) need to implement that method. Being 
a function means that it only needs to be implemented once.

But most of all, I expect it is because filter is an operation that 
comes from the functional programming school of thought, and modifying 
data structures in-place is anathema to functional programming.


-- 
Steven


More information about the Python-ideas mailing list