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 program to Count Even and Odd numbers in a List
In this article, we will learn how to count even and odd numbers in a Python list using three different approaches.
Problem statement ? We are given a list of integers, and we need to count how many are even and how many are odd.
Using For Loop (Brute Force)
The most straightforward approach is to iterate through each number and check if it's even or odd using the modulo operator ?
numbers = [21, 3, 4, 6, 33, 2, 3, 1, 3, 76]
even_count, odd_count = 0, 0
# Iterate through each number
for num in numbers:
# Check if number is even
if num % 2 == 0:
even_count += 1
# Otherwise it's odd
else:
odd_count += 1
print("Even numbers in the list:", even_count)
print("Odd numbers in the list:", odd_count)
Even numbers in the list: 4 Odd numbers in the list: 6
Using filter() and lambda
We can use Python's built-in filter() function with lambda expressions to filter even and odd numbers separately ?
numbers = [21, 3, 4, 6, 33, 2, 3, 1, 3, 76]
# Filter odd numbers and count them
odd_count = len(list(filter(lambda x: (x % 2 != 0), numbers)))
# Filter even numbers and count them
even_count = len(list(filter(lambda x: (x % 2 == 0), numbers)))
print("Even numbers in the list:", even_count)
print("Odd numbers in the list:", odd_count)
Even numbers in the list: 4 Odd numbers in the list: 6
Using List Comprehension
List comprehension provides a concise way to create lists based on conditions. We can count odd numbers directly and calculate even numbers ?
numbers = [21, 3, 4, 6, 33, 2, 3, 1, 3, 76]
# Create list of odd numbers and get its length
only_odd = [num for num in numbers if num % 2 == 1]
odd_count = len(only_odd)
# Even count = total - odd count
even_count = len(numbers) - odd_count
print("Even numbers in the list:", even_count)
print("Odd numbers in the list:", odd_count)
Even numbers in the list: 4 Odd numbers in the list: 6
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| For Loop | High | Good | Beginners, clear logic |
| filter() + lambda | Medium | Moderate | Functional programming style |
| List Comprehension | High | Good | Pythonic, concise code |
Conclusion
All three methods effectively count even and odd numbers in a list. The for loop approach is most readable for beginners, while list comprehension offers the most Pythonic solution. Choose based on your coding style and requirements.
