Python filter() function is used to filter elements from an iterable (list, tuple, etc.) for which a function returns
filter() function returns an iterator.
Python filter() function example
For simple example code a new list with only the values equal to or above 18:
ages = [5, 10, 15, 20, 25, 30] def myFunc(x): if x < 18: return False else: return True adults = filter(myFunc, ages) print(adults) print(type(adults)) print(list(adults))
Using Lambda Function Inside filter()
ages = [5, 10, 15, 20, 25, 30] res = filter(lambda x: (x % 2 == 0), ages) # converting to list even_numbers = list(res) print(even_numbers)
Output: [10, 20, 30]
Do comment if you have any doubts or suggestions on this Python basics function topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.