×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python filter() with Lambda Function

Last Updated : April 25, 2025

The filter() function is used to filter the elements from given iterable collection based on applied function.

The lambda function is an anonymous function - that means the function which does not have any name.

Implementing filter() with lambda function

You can use the filter() function with a lambda expression to filter elements from a sequence based on a specific condition.

The below is the syntax of using filter() with a lambda function in Python:

filter(lambda arguments: condition, iterable)

Example Using filter() with lambda

The following example demonstrates how to filter even numbers from a list using filter() with a lambda function:

# list of integers
fibo = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
print("Orignal List  :", fibo)

# filter even numbers using filter() and lambda
even = list(filter(lambda n: n % 2 == 0, fibo))
print("Even List     :", even)

The output of the above code will be:

Orignal List  : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Even List     : [0, 2, 8, 34] 

Explanation

  • List of Integers: The original list, fibo, contains the first few numbers of the Fibonacci sequence.
  • filter() with lambda: The filter() function is used to iterate through the fibo list and apply the lambda function to each element.
  • lambda Function: The lambda n: n % 2 == 0 function checks whether a number is even by dividing the number by 2 and checking if the remainder is 0.
  • Filtering Even Numbers: Only numbers that return True from the condition (n % 2 == 0) are included in the final list of even numbers.
  • Result: The result is a list of even numbers extracted from the original Fibonacci sequence, which is stored in the even list.

Python filter() with Lambda Exercise

Select the correct option to complete each statement about using filter() with lambda functions in Python.

  1. The filter() function returns elements for which the lambda function returns ___.
  2. filter(lambda x: x % 2 == 0, [1, 2, 3, 4]) will return:
  3. In Python 3, the result of filter() is a ___, not a list.

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.