Filter in Python

PythonServer Side ProgrammingProgramming

We sometimes arrive at a situation where we have two lists and we want to check whether each item from the smaller list is present in the bigger list or not. In such case we use the filter() function as discussed below.

Syntax

Filter(function_name, sequence name)

Here Function_name is the name of the function which has the filter criteria. Sequence name is the sequence which has elements that needs to be filtered. It can be sets, lists, tuples, or other iterators.

Example

In the below example we take a bigger list of some month names and then filter out those months which does not have 30 days. For that we create a smaller list containing the months with 31 days and then apply the filter function.

 Live Demo

# list of Months
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug']
# function that filters some Months
def filterMonths(months):
   MonthsWith31 = ['Apr', 'Jun','Aug','Oct']
if(months in MonthsWith31):
   return True
else:
   return False
non30months = filter(filterMonths, months)
   print('The filtered Months :')
for month in non30months:
   print(month)

Output

Running the above code gives us the following result −

The filtered Months :
Apr
Jun
Aug
raja
Published on 23-Aug-2019 12:29:22
Advertisements