Python program to count numbers of even and odd elements in an array

count even and odd elements in python

Count number of even and odd elements in Python

Here, in this page you will find the program to count number of even and odd elements in python programming language. We are given with an integer array and need to print the count of even elements and odd elements.

Here, we will discuss the following two methods to print the count of even elements and odd elements.

  • Method 1 : Using Modulo operator
  • Method 2 : Using Bit-wise AND operator.

Let’s discuss above two methods one by one,

Method 1 :

  • Take two variables, countEven=0, countOdd=0.
  • Iterate over the array,
  • Increment countEven if(arr[i]%2==0)
  • Otherwise increment the value of countOdd by 1.

Method 1 : Code in Python

Run
arr = [1, 7, 8, 4, 5, 16, 8]
n = len(arr)
countEven = 0
countodd = 0
for i in range(0, n):
    if arr[i]%2==0 :
        countEven += 1
    else:
        countodd += 1

print("Even Elements count : " )
print(countEven)

print("Odd Elements count : ")
print(countodd)

Output :

Even Elements count :
4
Odd Elements count :
3

Method 2 :

In this method we will use bit-wise AND operator. By doing AND of 1 with array element, if the result comes out to be 0 then the number is even otherwise odd.

Method 2 : Code in Python

Run
arr = [1, 7, 8, 4, 5, 16, 8]
n = len(arr)
countEven = 0
countodd = 0
for i in range(0, n):
    if arr[i]&1==0 :
        countEven += 1
    else:
        countodd += 1

print("Even Elements count : " )
print(countEven)

print("Odd Elements count : ")
print(countodd)

Output :

Even Elements count :
4
Odd Elements count :
3

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

2 comments on “Python program to count numbers of even and odd elements in an array”


  • Vikas Reddy Gorantla

    a=[1, 7, 8, 4, 5, 16, 8]
    even_count=0
    odd_count=0
    for i in a:
    if i%2==0:
    even_count+=1
    else:
    odd_count+=1
    print(even_count)
    print(odd_count)


  • Tanishka

    a = [1, 7, 8, 4, 5, 16, 8]
    c=0
    p=0
    for i in a:
    if(i%2==0):
    c+=1
    else:
    p+=1
    print(“even =”,c ,”odd =”, p)