I need to calculate just first five prime numbers. I want to check the length of list while building it in list comprehension. The following code doesn't work.
def checkPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
primes = []
primes = [x for x in range(2,30) if(checkPrime(x) and len(primes)<6) ]
print primes
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Why len(primes)<6
is not working here. How can I achieve that?
The "Pythonic" way is to use a generator, plus the islice
function:
from itertools import islice
def checkPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def primes():
i = 2
while True:
if checkPrime(i):
yield i
i += 1
first_5 = list(islice(primes, 5))
What this will do is create an infinite "list" called primes
that you can use in many ways that a list can be used, but it will only actually calculate the values that you need.