Search code examples
pythonlistif-statementlist-comprehensionprimes

Python- list of prime number in range one line code


How to write in one line method that checks if the number is prime or not in range of numbers? The return value is a list of prime/not each number in the range.

Output example: [“prime”, “not prime”...”not prime”' ,“prime]


Solution

  • This might be what you are looking for:

    # one line
    primes = ["prime" if num > 1 and len([i for i in range(2, int(num / 2+1)) if num % i == 0]) == 0 else "not prime" for num in num_list]
    
    # e.g.
    >>> num_list = [1,2,3,4,5,6,7,8,9,10,11]
    >>> primes = ["prime" if num > 1 and len([i for i in range(2, int(num / 2+1)) if num % i == 0]) == 0 else "not prime" for num in num_list]
    >>> primes
    ['not prime', 'prime', 'prime', 'not prime', 'prime', 'not prime', 'prime', 'not prime', 'not prime', 'not prime', 'prime']
    

    The inner list comprehension (i.e. [i for i in range(2, int(num / 2+1)) if num % i == 0]) is used to check whether the number has other factors apart from 1 and itself.