In Python, we can count the number of primes in a list by defining a function to check if a number is prime, and then looping through the list and adding up the count.

def isPrime(n):
    if (n % 2 == 0):
        return False
    for i in range(3, int(n**0.5 + 1), 2):
        if (n % i == 0):
            return False
    return True

def countPrimes(list_of_numbers):
    count = 0
    for num in list_of_numbers:
        if isPrime(num):
            count = count + 1
    return count

print(countPrimes([3,10,32,13,70]))

#Output: 
2

When working with lists of numbers, sometimes it can be useful to be able to count the number of primes.

In Python, we can count the number of primes in a list easily.

To count all the primes in a list, we can first define a function which checks if a number is prime.

def isPrime(n):
    if (n % 2 == 0):
        return False
    for i in range(3, int(n**0.5 + 1), 2):
        if (n % i == 0):
            return False
    return True

Then, to count the number of primes in a list, all we need to do is loop over each element in the list and count the primes.

Below is a Python function which will count the number of primes in a list.

def isPrime(n):
    if (n % 2 == 0):
        return False
    for i in range(3, int(n**0.5 + 1), 2):
        if (n % i == 0):
            return False
    return True

def countPrimes(list_of_numbers):
    count = 0
    for num in list_of_numbers:
        if isPrime(num):
            count = count + 1
    return count

print(countPrimes([3,10,32,13,70]))

#Output: 
2

Counting All of the Primes in a Range of Numbers

We can also use our isPrime() function to count the number of primes in a range of numbers.

To get the number of primes in a range, we can define a function which will take in two numbers, the endpoints of our range, and then loop over the odd numbers in that range.

A few things to consider in our prime counting function. First, if one of the endpoints is 2, then we should also add another to our count. Also, if the bottom endpoint is even, we need to make it odd.

Below is a Python function which will get the number of primes between two numbers.

def getPrimeCount(a,b):
    if a > 1 and b > 1:
        count = 0
        if a > b:
            t = a
            a = b
            b = t
        if a == 2:
            count = 1
            a = 3
        if a % 2 == 0: 
            a = a + 1
        while (a < b):
            if(isPrime(a)):
                count = count + 1
            a = a + 2
        return count
    else:
        return "Not a valid range."

print(getPrimeCount(3,13))
print(getPrimeCount(100,1000))
print(getPrimeCount(200,400))
print(getPrimeCount(21,34))

#Output:
4
143
32
3

Hopefully this article has been helpful for you to count the number of primes in a list using Python.

Categorized in:

Python,

Last Update: February 26, 2024