In this example, you will find and count odd/even numbers from list.
Example 1: Using Loop
# Python program to count even and odd number using loop
list1 = [1,2,3,4,5,6,7,8,9]
even_count, odd_count = 0, 0
num = 0
# using while loop
while(num < len(list1)):
if list1[num] % 2 == 0:
even_count += 1
else:
odd_count += 1
num += 1
print("Even numbers in the list: ", even_count)
print("Odd numbers in the list: ", odd_count)
Output :
Even numbers in the list: 4
Odd numbers in the list: 5
Explanation :
The logic of the program is simple, we iterate through each element of the list and check its remainder after dividing by 2. If the remainder is 0 then it is even number so we increment even counter, else it is an odd number and we increment the odd counter.
Example 2: Using Lambda
# Python program to count even and odd number using lambda function
list1 = [1,2,3,4,5,6,7,8,9]
even_count = list(filter(lambda x: (x % 2 == 0), list1))
odd_count = list(filter(lambda x: (x % 2 != 0), list1))
print("Even numbers in the list: ", len(even_count))
print("Odd numbers in the list: ", len(odd_count))
Output :
Even numbers in the list: 4
Odd numbers in the list: 5
Explanation :
Lambda functions are anonymous functions which are kind of instant run functions. Here, we create two separate even and odd list using filter function count the length of each.
Example 3: Using List Comprehension
# Python program to count even and odd number using list comprehension
list1 = [1,2,3,4,5,6,7,8,9]
only_odd = [num for num in list1 if num % 2 == 1]
odd_count = len(only_odd)
print("Even numbers in the list: ", len(list1) - odd_count)
print("Odd numbers in the list: ", odd_count)
Output :
Even numbers in the list: 4
Odd numbers in the list: 5
Explanation :
Here, create a new list be selecting only even elements. At last, we count the elements to get even numbers in the list and calculate odd numbers count.
Ask anything about this examples