Help With filter().

James Logajan JamesL at Lugoj.Com
Wed Jul 11 23:16:52 EDT 2001


EricIDLE wrote:
> 
> I Still Dont Get It. Could you explain it in simpiler terms?

How good is your Python? Do you know about lists and how to manipulate them
and how to use "for" loops? Do you understand that variables can be assigned
references to functions and that a function can take a function reference as
an argument? If you are unclear on any of that, then that may be why my
explanation is unclear. Or more likely I did not explain very well, so I'll
try again:

How about: "filter" takes a reference to a filtering function and a list,
and returns a subset of the supplied list. Try some examples:

# This function returns true if given a number larger
# than 23 and false for all other numbers.
def MyFunc(listItem):
    return listItem > 23

So the following call:

filter(MyFunc, [10, 22, 23, 24, 5, 30, 45])

would return another list containing only those elements for which MyFunc
returns true:

[24, 30, 45]

Now if you don't supply a function, the items themselves are tested for
"truthness" as Python defines it. Try the following:

filter(None, [10, 0, None, 23, -3, "", "hi", [], "the end"])

Since Python considers 0, None, "", and empty lists [] as having "false"
truth values when used in boolean expressions, they are filtered out and you
would get everything else, which Python considers has a "true" value in
boolean expressions:

[10, 23, -3, 'hi', 'the end']

You need to run the Python interpreter and use the interactive mode and
start playing around with it. Experimenting more may answer a lot of your
questions.



More information about the Python-list mailing list