

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
What is filter() in python?
Through the filter method, we filter out specific elements of a list using a filter condition defined in a separate function. So we first create a user-defined function which will mention the criteria of filtering. Together this function and the supplied list will be taken as parameters to the filter function to give us the result.
Syntax
filter(filter_function, sequence)
Example
In the below example we create a function that will find the even numbers present in a list. Then it will discard them (return false). The remaining odd numbers will be added to the final list. We can modify this function to filter out numbers divisible by 3 or 5 or so.
num_list = [6,17, 32, 11, 21, 132] def remove_even(x): if x%2 ==0 : return False else: return True odd_nos = filter(remove_even, num_list) for x in odd_nos: print(x)
Output
Running the above code gives us the following result −
17 11 21
Example
We can use the same approach to filter out vowels from a given list of alphabets. Here
letters = ['t','u','t','o','r','i','a','l','s'] def get_vowels(c): if c in ['a','e','i','o','o']: return True else: return False vowel_list = filter(get_vowels, letters) for w in vowel_list: print(w)
Output
Running the above code gives us the following result −
u o i a
- Related Questions & Answers
- What is Ideal Reconstruction Filter?
- Filter in Python
- What is an I/O filter in Java?
- Example filter() in python
- What is the role of filter() method in JavaScript?
- Python - Filter Supersequence Strings
- What is the difference between filter() and find() in jQuery?
- What is the difference between Grep and Filter in jQuery?
- Lambda and filter in Python Examples
- Lambda and filter Examples in Python
- Python – Filter Sorted Rows
- Python – Filter Tuples with Integers
- Python – Filter unique valued tuples
- Python – Filter consecutive elements Tuples
- Python - Filter Pandas DataFrame with numpy