Python program to Count Even and Odd numbers in a List


In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given a list, we need to count even and odd numbers in a list.

There are three methods as discussed below−

Approach 1 − Using brute-force approach

Example

 Live Demo

list1 = [21,3,4,6,33,2,3,1,3,76]
even_count, odd_count = 0, 0
# enhanced for loop
for num in list1:
   #even numbers
   if num % 2 == 0:
      even_count += 1
   #odd numbers
   else:
      odd_count += 1
print("Even numbers available in the list: ", even_count)
print("Odd numbers available in the list: ", odd_count)

Output

Even numbers available in the list: 4
Odd numbers available in the list: 6

Approach 2 − Using filter() and lambda expressions

Example

 Live Demo

list1 = [21,3,4,6,33,2,3,1,3,76]
#odd numbers
odd_count = len(list(filter(lambda x: (x%2 != 0) , list1)))
#even numbers
even_count = len(list(filter(lambda x: (x%2 == 0) , list1)))
print("Even numbers available in the list: ", even_count)
print("Odd numbers available in the list: ", odd_count)

Output

Even numbers available in the list: 4
Odd numbers available in the list: 6

Approach 3 − Using the list comprehension

Example

 Live Demo

list1 = [21,3,4,6,33,2,3,1,3,76]
#copy of list elements which are odd in a new list and calculating
the length on new list
only_odd = [num for num in list1 if num % 2 == 1]
odd_count = len(only_odd)
print("Even numbers available in the list: ", len(list1) -
odd_count)
print("Odd numbers available in the list: ", odd_count)

Output

Even numbers available in the list: 4
Odd numbers available in the list: 6

Conclusion

In this article, we have learned how to count even and odd numbers in a list.

Updated on: 11-Jul-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements