Thursday, 29 December 2016

Python filter() Function

Python filter() Function - We have been learning some of the important utilities used in function programming that includes functions – map(), reduce() and filter(). We have already covered map() function and reduce() in our recent articles. In this article, we will learn about filter() function. Let’s begin with the discussion straight away.

python-filter-function

Using reduce() with lambdas

As the name suggests, filter() function filters out some elements from a sequence. Just like map() and reduce() functions, this function receives two arguments – a function and an iterable object. The function is usually called as filter and returns either True or False. This function is then executed on each element of the iterable. As a result, we get a list of items for which the filter returns True.

Don’t be afraid, if its difficult to understand, we will see some examples and explain them in details. To begin with, we try to extract even number from a list of numbers. We need to create the filter, at first. We can use a normal function or a lambda, but it should return either True or False only, nothing else.

Syntax:

filter( function, iterable_object )

Example :

# Create the data set
>>> myList = range(1,16)
>>> myList
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# A very simple filter
>>> def filterEven(num):
...     if num % 2 == 0:
...             return True
...     else:
...             return False
...

# Output
>>> print filter(filterEven, myList)
[2, 4, 6, 8, 10, 12, 14]

# A better version of above filter
>>> def filterEven(num):
...     return num % 2 == 0
...

# Output
>>> print filter(filterEven, myList)
[2, 4, 6, 8, 10, 12, 14]

# Using a lambda function
>>> filterEven = lambda num : num % 2 == 0

# Output
>>> print filter(filterEven, myList)
[2, 4, 6, 8, 10, 12, 14]

# Using lambda directly inside 'filter()'
>>> print filter(lambda num : num % 2 == 0, myList)
[2, 4, 6, 8, 10, 12, 14]

How it works

In the above examples, we have a function that returns True if a number is even, False otherwise. So, it will start iterating through the iterable, and pass the item to the function as an argument. If for a particular item, function returns True, it is added to the output list, otherwise skipped. In the end, we get a list of all those items for which function has retuned True. If we were to write an equivalent code to have the same behavior, code would have looked like -

>>> def myFilter(varList):
...     result = []
...     for i in varList:
...             if i % 2 == 0:
...                     result.append(i)
...     return result
...

>>> myList
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

>>> myFilter(myList)
[2, 4, 6, 8, 10, 12, 14]

We take another simple example. In this, we will filter the non-negative numbers from a sequence of numbers. The logic to construct a filter is very simply and should be clear.

# Create the test data
>>> myList = range(-10,11)
>>> myList
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Create the filter
>>> def filterNonNegative(num):
...     return num >= 0
...

# Use filter with the list in 'filter()'
>>> print filter(filterNonNegative, myList)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using lambda inside 'filter()'
>>> print filter(lambda num : num >= 0, myList)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In the next example, we work on a list of strings, may be a list of names of continents, and filter out the ones who have less than 8 characters in them. Pretty simple, isn’t it?

# List of continents
>>> myList = ['Asia', 'Africa', 'Australia', 'Europe', 'North America', 'South America', 'Antarctica']

# The filter 
>>> def filterSmall(myStr):
...     return len(myStr) < 8
...

# Output
>>> print filter(filterSmall, myList)
['Asia', 'Africa', 'Europe']

# With lambda inside 'filter()'
>>> print filter(lambda myStr : len(myStr) < 8, myList)
['Asia', 'Africa', 'Europe']

With this, we close our discussion on filter() function. It was pretty straight forward to understand and use. We just need a
filter - a function which returns Boolean values and an iterable. As a result, we get a list with items for which filter returned True. Please share your views and feedback in the comments section below and stay tuned for more articles. Thank you.

0 comments:

Post a Comment