Counting the Number of Even and Odd Elements in an Array in Python

Understanding Even and Odd Count

This task involves counting the number of even and odd elements in an array.

We will explore three different methods to achieve this in Python.

Method 1: Using Loop

This method iterates through the array and counts even and odd elements.

def count_even_odd(arr):
    even_count = sum(1 for num in arr if num % 2 == 0)
    odd_count = len(arr) - even_count
    print(f"Even Count: {even_count}, Odd Count: {odd_count}")

arr = [1, 2, 3, 4, 5, 6, 7, 8]
count_even_odd(arr)
            
Output:
Even Count: 4, Odd Count: 4

Method 2: Using Recursion

This method counts even and odd numbers using recursion.

def count_even_odd_rec(arr, index=0, even_count=0, odd_count=0):
    if index == len(arr):
        print(f"Even Count: {even_count}, Odd Count: {odd_count}")
        return
    if arr[index] % 2 == 0:
        even_count += 1
    else:
        odd_count += 1
    count_even_odd_rec(arr, index + 1, even_count, odd_count)

arr = [1, 2, 3, 4, 5, 6, 7, 8]
count_even_odd_rec(arr)
            
Output:
Even Count: 4, Odd Count: 4

Method 3: Using List Comprehension

This method uses list comprehension to determine even and odd numbers.

def count_even_odd(arr):
    even_count = len([num for num in arr if num % 2 == 0])
    odd_count = len(arr) - even_count
    print(f"Even Count: {even_count}, Odd Count: {odd_count}")

arr = [1, 2, 3, 4, 5, 6, 7, 8]
count_even_odd(arr)
            
Output:
Even Count: 4, Odd Count: 4
Top 100 Codes By Learn-for-free
Start Preparing Arraysform here👇

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

Find Largest Element in an Array: C C++ Java Python

Find Smallest Element in an Array: C C++ Java Python

Find the Smallest and Largest Element in an Array: C C++ Java Python

Find Second Smallest Element in an Array: C C++ Java Python

Calculate the Sum of Elements in an Array: C C++ Java Python

Reverse an Array: C C++ Java Python

Sort First Half in Ascending Order and Second Half in Descending: C C++ Java Python

Finding the Frequency of Elements in an Array: C C++ Java Python

Counting the Number of Even and Odd Elements in an Array: C C++ Java Python

Finding Maximum Product Sub-array in a Given Array: C C++ Java Python

Finding Arrays are Disjoint or Not: C C++ Java Python

Finding Equilibrium Index of an Array: C C++ Java Python

Rotation of Elements of Array - Left and Right: C C++ Java Python

Balanced Parenthesis Problem: C C++ Java Python