Python filter() function
The filter() method facilitates a functional approach to Python programming . It allows the developer to write simpler, shorter code , without necessarily needing to bother about intricacies like loops and branching.
The filter() method returns an iterator were the items are filtered through a function to test if the item is accepted or not. The returned iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None , the identity function is assumed, that is, all elements of iterable that are false are removed. Syntax
filter(function, iterable)
- function : The function that tests if elements of an iterable returns true or false.
- iterable : The iterable to be filtered.
How to filter a list in Python
# The function that tests if elements of an iterable returns true or false
def foo(var):
directions = ['east', 'west', 'north', 'south']
if (var in directions):
return True
else:
return False
# The list to be filtered
myList = ['sunday', 'east', 'march', 'west', '101', 'north', 'abcd', 'south']
# using filter function
filtered = filter(foo, myList)
print('Filtered directions are:')
for str in filtered:
print(str)
output
Filtered directions are:
east
west
north
south

Python filter using lambda expression
myList = [10, 15, 40, 6, 30, -20]
# Returns the elements which are multiples of 10
filtered = list(filter(lambda n : n%10 == 0, myList))
print(filtered)
output
[10, 40, 30, -20]
Related Topics
- How to use Date and Time in Python
- Python Exception Handling
- How to Generate a Random Number in Python
- How to pause execution of program in Python
- How do I parse XML in Python?
- How to read and write a CSV files with Python
- Threads and Threading in Python
- Python Multithreaded Programming
- Python range() function
- How to Convert a Python String to int
- Difference between range() and xrange() in Python
- How to print without newline in Python?
- How to remove spaces from a string in Python
- How to get the current time in Python
- Slicing in Python
- Create a nested directory without exception | Python
- How to measure time taken between lines of code in python?
- How to concatenate two lists in Python
- How to Find the Mode in a List Using Python
- Difference Between Static and Class Methods in Python?