0
0
Pythonprogramming~5 mins

Lambda with filter() in Python

Choose your learning style9 modes available
Introduction

Lambda with filter() helps you quickly pick items from a list that match a rule, without writing a full function.

When you want to find all even numbers in a list.
When you need to select words longer than 5 letters from a list.
When filtering out empty strings from user input.
When you want to keep only positive numbers from a list.
Syntax
Python
filter(lambda item: condition, iterable)

The lambda is a small, unnamed function used to test each item.

filter() returns an iterator with items where the lambda returns True.

Examples
This picks even numbers from the list.
Python
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
This keeps words longer than 3 letters.
Python
words = ['apple', 'bee', 'cat', 'dolphin']
long_words = list(filter(lambda w: len(w) > 3, words))
print(long_words)
Sample Program

This program filters the list of fruits to keep only those with names longer than 4 letters.

Python
fruits = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape']
# Select fruits with names longer than 4 letters
long_fruits = list(filter(lambda fruit: len(fruit) > 4, fruits))
print(long_fruits)
OutputSuccess
Important Notes

Remember to convert the filter result to a list if you want to see all items at once.

Lambda functions are quick but can be harder to read if too complex.

Summary

Use filter() with a lambda to pick items matching a condition.

It helps keep code short and clear for simple filtering tasks.