Tuesday, 25 November 2008

Hey man, nice shot .. aka filter

Filter is another of those incredibly handy built-in python functions. It takes a function and a list, and filters the elements of the list using the function:

filter(f, a)

So say we want to filter out all those pesky Nones from a list where Nones have no right to be: [1, None, 2, 3, None, 4]. We could go down the iterate through the list, creating a new list from all the non-null elements ... but that requires multiple lines of tedium.

Instead we employ the power of filter() and -- wait for it -- a lambda function!

filter(lambda x: x != None, [1, None, 2, 3, None, 4])

And presto! The Nones are no more.

No comments: