Introduction
Lambda with filter() helps you quickly pick items from a list that match a rule, without writing a full function.
Jump into concepts and practice - no test required
Lambda with filter() helps you quickly pick items from a list that match a rule, without writing a full function.
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.
numbers = [1, 2, 3, 4, 5] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers)
words = ['apple', 'bee', 'cat', 'dolphin'] long_words = list(filter(lambda w: len(w) > 3, words)) print(long_words)
This program filters the list of fruits to keep only those with names longer than 4 letters.
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)
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.
Use filter() with a lambda to pick items matching a condition.
It helps keep code short and clear for simple filtering tasks.
filter(lambda x: x > 5, [2, 7, 4, 10])nums using lambda and filter?nums = [1, 3, 6, 8, 11] result = list(filter(lambda x: x < 7, nums)) print(result)
nums = [10, 15, 20] filtered = filter(lambda x: x % 2 = 0, nums) print(list(filtered))
words = ['apple', '', 'banana', ' ', 'cherry', None]. Which code correctly filters out empty strings, strings with only spaces, and None values using lambda and filter?