Function to check whether entire list is prime numbers I have a prime function which accepts a list of numbers and checks if all of the numbers in the list are prime.

Here is my code:

from math import sqrt
def primes(lista):
    return all(True if n == 2 else bool(all(n % x for x in list(range(3, int(sqrt(n)+1), 2))+ [2])) for n in lista)


Can I make this code more readable without making the actual function slower?
There are a few obvious improvements, which either make it more readable or even faster:


True if n == 2 else ... is equivalent to n == 2 or ...
bool(all(...)) is the same as all()
You could pull out the special case of 2 in all(n % x for x in list(range(3, int(sqrt(n)+1), 2))+ [2]) by doing (n % 2 and all(n % x for x in range(3, int(sqrt(n)+1), 2))). 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.


This gives:

from math import sqrt

def primes(lista):
    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)


But if you really want to make it more readable, you should factor out the prime check into another function:

from math import sqrt

def is_prime(n):
    """Check if `n` is prime.

    Uses exhaustive search to look for factors up to sqrt(n) + 1.
    """
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    return all(n % x for x in range(3, int(sqrt(n) + 1), 2))


def all_primes(lista):
    """Check if all numbers in `lista` are primes."""
    return all(is_prime(n) for n in lista)


Another alternative is to compute a set of primes once and then just check if all of them are in this set:

primes_set = set(prime_sieve(100000))

def all_primes_set(lista):
    lista_set = set(lista)
    return len(primes_set &amp; lista_set) == len(lista_set)


On my machine all of these are faster than your original function:

primes_list = list(prime_sieve(100000))

%timeit primes_op(primes_list)
77.3 ms ± 373 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit primes(primes_list)
67.8 ms ± 706 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit all_primes(primes_list)
70.9 ms ± 235 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit all_primes_set(primes_list)
823 µs ± 9.53 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


So if you know what the largest number is which you need to check, checking against a set that is computed only once is the fastest.