Reference Materials
Created with over a decade of experience.
Certification Courses
Created with over a decade of experience and thousands of feedback.
Built-in Functions
- Python abs()
- Python any()
- Python all()
- Python ascii()
- Python bin()
- Python bool()
- Python bytearray()
- Python callable()
- Python bytes()
- Python chr()
- Python compile()
- Python classmethod()
- Python complex()
- Python delattr()
- Python dict()
- Python dir()
- Python divmod()
- Python enumerate()
- Python staticmethod()
- Python filter()
- Python eval()
- Python float()
- Python format()
- Python frozenset()
- Python getattr()
- Python globals()
- Python exec()
- Python hasattr()
- Python help()
- Python hex()
- Python hash()
- Python input()
- Python id()
- Python isinstance()
- Python int()
- Python issubclass()
- Python iter()
- Python list() Function
- Python locals()
- Python len()
- Python max()
- Python min()
- Python map()
- Python next()
- Python memoryview()
- Python object()
- Python oct()
- Python ord()
- Python open()
- Python pow()
- Python print()
- Python property()
- Python range()
- Python repr()
- Python reversed()
- Python round()
- Python set()
- Python setattr()
- Python slice()
- Python sorted()
- Python str()
- Python sum()
- Python tuple() Function
- Python type()
- Python vars()
- Python zip()
- Python __import__()
- Python super()
Python filter()
The filter() function selects elements from an iterable based on the result of a function.
Example
# returns True if the argument passed is even
def check_even(number):
if number % 2 == 0:
return True
return False
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# if an element passed to check_even() returns True, select it
even_numbers_iterator = filter(check_even, numbers)
# converting to list
even_numbers = list(even_numbers_iterator)
print(even_numbers)
# Output: [2, 4, 6, 8, 10]
filter() Syntax
filter(function, iterable)
filter() Parameters
The function takes two parameters:
- function - a function that runs for each item of an iterable
- iterable - a sequence that needs to be filtered like sets, lists, tuples, etc
filter() Return Value
The filter() function returns an iterator.
Example: Filter Vowels From List
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
# a function that returns True if letter is vowel
def filter_vowels(letter):
vowels = ['a', 'e', 'i', 'o', 'u']
if letter in vowels:
return True
else:
return False
# selects only vowel elements
filtered_vowels = filter(filter_vowels, letters)
# converting to tuple
vowels = tuple(filtered_vowels)
print(vowels)
# Output: ('a', 'e', 'i', 'o')
Here's how the above program works:
- each element of
lettersis passed to thefilter_vowels()function - if
filter_vowels()returnsTrue, filter() selects the element
Note: Here, the program returns the iterator, which we converted into a tuple using the vowels = tuple(fitered_vowels).
More on Python filter()
We can also use the Python filter() function with the lambda function. For example,
numbers = [1, 2, 3, 4, 5, 6, 7]
# the lambda function returns True for even numbers
even_numbers_iterator = filter(lambda x: (x%2 == 0), numbers)
# converting to list
even_numbers = list(even_numbers_iterator)
print(even_numbers)
# Output: [2, 4, 6]
In the above example, the lambda function returns True only for even numbers. Hence, the filter() function returns an iterator containing even numbers only.
When None is used as the first argument to the filter() function, it extracts all elements that evaluate to True when converted to boolean. For example,
random_list = [1, 'a', 0, False, True, '0']
filtered_iterator = filter(None, random_list)
# converting to list
filtered_list = list(filtered_iterator)
print(filtered_list)
# Output: [1, 'a', True, '0']
Here, 1, 'a' , True and '0' are considered True on conversion to booleans.
Also Read:
