Help With filter().

Nick Efford nde at comp.leeds.ac.uk
Thu Jul 12 08:34:15 EDT 2001


On Wed, 11 Jul 2001 23:48:07 GMT, EricIDLE <grayson-wilson at home.com> wrote:

> What does filter do? I don't understand when I read it other places.

Think about the general concept of filtering; filters let some
things pass through and block others.  Python's filter function
does exactly this for sequences - letting certain items from
the sequence through and blocking others.  The filter function
returns a new sequence which is a subset of the input sequence.

Of course, you need some way of specifying which items should
pass through the filter.  You do this by defining a function
that takes a single argument, returning true if that value should
be pass through the filter and false if it should be eliminated
by the filter.  Unless we need this function for some other
purpose, a lambda expression will suffice.

Example: filtering out odd numbers from a list of integers.
We can use a lambda expression that tests whether we get
a remainder of zero when dividing a value by 2; if so, the
value is even and should be retained.

>>> data = range(10)
>>> data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> filter(lambda x: x%2 == 0, data)
[0, 2, 4, 6, 8]

A more useful example is filtering a list of directory entries:

>>> import os
>>> os.listdir('.')
['Start.py', 'doc.py', 'doc.pyc', 'Gnuplot', 'SIPlib', 'doc',
'tests', 'programs', 'README']

Some of the items in the list are the names of files; others
are the names of subdirectories.  We can generate a list
containing only the subdirectories like so:

>>> filter(os.path.isdir, os.listdir('.'))
['Gnuplot', 'SIPlib', 'doc', 'tests', 'programs']

To generate a list containing only the plain files, we do:

>>> filter(os.path.isfile, os.listdir('.'))
['Start.py', 'doc.py', 'doc.pyc', 'README']

Since Python 2.0, many uses of filter can be replaced by
list comprehensions, which are often more readable:

>>> [x for x in data if x%2 == 0]
[0, 2, 4, 6, 8]

HTH,


Nick




More information about the Python-list mailing list