Skip to content

Python filter list lambda

  • by

You can use the lambda function in the list for filter list in Python. The filtering condition function is often dynamically created using lambda functions.

An inline function may be defined with the help of lambda expressions. The syntax of the lambda function is lambda x: expression and it means that you use x as an input argument and you return expression as a result

 Lambda arguments: expression

Python filter list lambda example

Simple example code filter out all the even numbers from the given list.

inp_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
res = list(filter(lambda x: x % 2 == 0, inp_list))

print(res)
print(type(res))

Output:

Python filter list lambda

Another example

numbers = [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]
print("List of numbers:")
print(numbers)

print("\nList of even numbers:")
evenNumbers = list(filter(lambda x: x%2 == 0, numbers))
print(evenNumbers)

print("\nList Odd numbers:")
oddNumbers = list(filter(lambda x: x%2 != 0, numbers))
print(oddNumbers)

Do comment if you have any doubts or suggestions on this Python filter topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.