Whichever of these 2 is best depends mainly on preference method 2: def get_primes_to(x):Ĭhecking whether all elements of lista are primes can also be done with set. This can be rewritten with map def test_primes(lista): This is basically what you did, but with an inline, slow check for primes def isprime(x): There are a lot alternative on the web and SO. Here you can choose the algorithm most suited for your need. I will not get into details on which method to generate all the primes to max(lista), or the prime check. If there are a lot, smaller elements, the 2nd method is faster, for a few, larger elements, method 1 will be better. Which of the 2 options is better depends on lista.
![how to find list of prime numbers how to find list of prime numbers](https://d20khd7ddkh5ls.cloudfront.net/prime_and_composite_numbers_1-100_2.jpg)
Uses exhaustive search to look for factors up to sqrt(n) + 1. Return all(n = 2 or (n % 2 and all(n % x for x in range(3, int(sqrt(n)+1), 2))) for n in lista)īut if you really want to make it more readable, you should factor out the prime check into another function: from math import sqrt This has the advantage that the range does not get consumed into a list which makes this stop generating values as soon as a value is found not to be prime.
![how to find list of prime numbers how to find list of prime numbers](https://i.ytimg.com/vi/s079xnGeJfE/maxresdefault.jpg)
There are a few obvious improvements, which either make it more readable or even faster: