Python Practice › List Programs › Program 82
Prime numbers in a list
Write a Python program to get the prime numbers from a list.
Input
[11, 8, 7, 19, 6, 29]
Output
[11, 7, 19, 29]
Approach
- Keep numbers with no divisor from 2 to √n.
Solution
def is_prime(n): return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1)) print([n for n in [11, 8, 7, 19, 6, 29] if is_prime(n)])Output
[11, 7, 19, 29]
Learn the concept
New to this topic? Read the lesson, then come back.