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.
How to filter a list in Python
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)
  1. function : The function that tests if elements of an iterable returns true or false.
  2. 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


How to use the filter() method in Python

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]