Count Prime Numbers in List in Python

Count how many prime numbers are present in a list of integers.

IntermediateList ProgramsExample 22 of 25
count-prime-numbers-in-list.py
Run in browser
1# Program to count prime numbers in a list
2
3def is_prime(n: int) -> bool:
4 if n < 2:
5 return False
6 for i in range(2, int(n ** 0.5) + 1):
7 if n % i == 0:
8 return False
9 return True
10
11numbers = list(map(int, input("Enter integers separated by space: ").split()))
12
13count = sum(1 for x in numbers if is_prime(x))
14
15print("Number of primes in list:", count)

Output

Enter integers separated by space: 2 3 4 5 6
Number of primes in list: 3

What's going on

We define a helper is_prime and count how many list elements satisfy it.