 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter in Python
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.
# 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
Advertisements
 