Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
85 views
in Python by (176k points)
retagged by
How do I use a lambda function with filter()?

Please log in or register to answer this question.

1 Answer

0 votes
by (176k points)

You can use a lambda function with the filter() function in Python to filter elements from a sequence based on a condition. The filter() function takes two arguments: a function that returns a Boolean value, and a sequence to filter. It returns a new sequence containing only the elements of the original sequence for which the function returned True. Here is an example:

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
 

In this example, we have a list of numbers from 1 to 6. We want to create a new list containing only the even numbers from this list. We use the filter() function along with a lambda function to accomplish this.

The lambda function takes one argument x, which represents an element from the numbers list. The lambda function returns True if x % 2 == 0 (i.e., if x is even) and False otherwise. The filter() function applies this lambda function to each element of the numbers list, and returns a new list containing only the elements for which the lambda function returned True.

We assign this new list to the variable even_numbers, and then print it to the console using the print() function. The output of this code will be [2, 4, 6], which is the list of even numbers from the original list.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...