Generate a list of prime numbers from 1 to 50


The provided Python code defines a function is_prime(n) that checks whether a given integer n is a prime number or not. It then creates a list called prime_numbers using a list comprehension to find and store prime numbers between 1 and 50. Here's how the code works:

  • def is_prime(n): This line defines a function named is_prime that takes an integer n as an argument.
    • if n <= 1:: This line checks if n is less than or equal to 1. If n is 1 or less, it returns False, as 1 and any negative number are not prime.
    • for i in range(2, int(n**0.5) + 1):: This line sets up a loop that iterates from 2 to the square root of n (inclusive) using the range() function. Checking up to the square root is an optimization to reduce the number of divisions needed to determine primality.
    • if n % i == 0:: Inside the loop, this line checks if n is divisible by the current value of i. If it is, it means n is not prime, so the function returns False.
    • If none of the conditions above are met, it means n is not divisible by any number in the range, so the function returns True, indicating that n is a prime number.
  • prime_numbers = [x for x in range(1, 51) if is_prime(x)]: This line of code initializes a variable named prime_numbers and assigns it the result of a list comprehension.
    • for x in range(1, 51): This part sets up a loop that iterates through numbers from 1 to 50 (inclusive). The range(1, 51) function generates a sequence of numbers starting from 1 and ending at 50.
    • if is_prime(x): This condition checks if the current value of x is a prime number by calling the is_prime() function. If it is prime, it includes it in the prime_numbers list.
  • print(prime_numbers): This line of code prints the prime_numbers list to the console.

Source Code

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True
 
prime_numbers = [x for x in range(1, 51) if is_prime(x)]
print(prime_numbers)

Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Example Programs