Working with filters

True to its name, filter filters elements from a sequence based on the given function. With a sequence of negative and positive numbers, we can use a filter function to, say, filter out all the negative numbers. Filter is a built-in Python function. It takes a function and an iterable for an argument:

Filter(aFunction, iterable)

The function that is passed as an argument is returned as a Boolean value based on a test.

The function is applied on all the elements of the iterable and all the items that are returned as true when the function is applied over them are returned as a list. An anonymous function, lambda, is most commonly used along with filter.

Getting ready

Let's look at a simple code to see the filter function in action.

How to do it…

Let's see an example on how to use a filter function:

# Let us declare a list.
a = [10,20,30,40,50]
# Let us apply Filter function on all the elements of the list.
print filter(lambda x:x>10,a)

How it works…

The lambda function that we use here is very simple; it returns true if the given value is greater than ten, false otherwise. Our print statement gives the following result:

[20, 30, 40, 50]

As you can see, only elements greater than ten are returned.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset