Open In App

Filter Even Values from a List – Python

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of filtering even values from a list in Python involves selecting elements from the list that are even numbers. For example, given the list a = [1, 2, 3, 4, 5], the goal is to filter out the even values, resulting in a new list like this [2, 4].

Using list comprehension

List comprehension provides a efficient way to filter values from a list. It is often the most Pythonic and recommended approach for filtering, as it is both readable and fast. The syntax is compact and the operation is performed in a single line.

Python
a = [1, 2, 3, 4, 5]

res = [num for num in a if num % 2 == 0]
print(res)

Output
[2, 4]

Explanation: list comprehension iterates over each element in a and includes it in res only if it’s even (num % 2 == 0).

Using filter

filter() allows us to filter elements from an iterable based on a function. Combined with a lambda function, it offers a very compact and functional programming approach to filtering even values.

Python
a = [1, 2, 3, 4, 5]

res = list(filter(lambda num: num % 2 == 0, a))
print(res)

Output
[2, 4]

Explanation: filter() applies the lambda function to each element in a. The lambda num: num % 2 == 0 checks if a number is even and filter() returns an iterator with only the even numbers, which is then converted to a list using list().

Using for loop

For loop is the traditional and manual approach to iterate over a list and filter values. While it works perfectly fine, it is not as efficient or compact as the other methods. We manually check each element and append the even values to a new list.

Python
a = [1, 2, 3, 4, 5]
res = []

for num in a:
    if num % 2 == 0:
        res.append(num)
print(res)

Output
[2, 4]

Explanation: For loop iterates over each element in the list a. For each element, it checks if the number is even using the condition num % 2 == 0. If the condition is true, the number is added to the res list using append() .



Next Article
Practice Tags :

Similar Reads