Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Filter even values from a list
As part of data analysis, we often need to filter values from a list meeting certain criteria. In this article, we'll see how to filter out only the even values from a list.
To identify even numbers, we check if a number is divisible by 2 (remainder is zero when divided by 2). Python provides several approaches to filter even values from a list.
Using for Loop
This is the simplest way to iterate through each element and check for divisibility by 2 ?
numbers = [33, 35, 36, 39, 40, 42]
even_numbers = []
for n in numbers:
if n % 2 == 0:
even_numbers.append(n)
print(even_numbers)
[36, 40, 42]
Using While Loop
When working with lists of unknown lengths, a while loop with the len() function provides more control over iteration ?
numbers = [33, 35, 36, 39, 40, 42]
even_numbers = []
i = 0
while i < len(numbers):
if numbers[i] % 2 == 0:
even_numbers.append(numbers[i])
i += 1
print(even_numbers)
[36, 40, 42]
Using filter() with Lambda
The filter() function combined with a lambda expression provides a functional programming approach ?
numbers = [33, 35, 36, 39, 40, 42] is_even = lambda x: x % 2 == 0 even_numbers = list(filter(is_even, numbers)) print(even_numbers)
[36, 40, 42]
Using List Comprehension
List comprehension offers the most Pythonic and concise way to filter even numbers ?
numbers = [33, 35, 36, 39, 40, 42] even_numbers = [n for n in numbers if n % 2 == 0] print(even_numbers)
[36, 40, 42]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| for loop | High | Good | Beginners |
| while loop | Medium | Good | Complex conditions |
| filter() | Medium | Good | Functional programming |
| List comprehension | High | Best | Pythonic code |
Conclusion
List comprehension is the most efficient and Pythonic way to filter even numbers. Use filter() for functional programming style, and loops when you need more complex logic or are learning Python basics.
