Generate a list of pairs of numbers where the sum of each pair is prime


This Python code defines a function is_prime(n) to check if a given number n is prime or not. Then, it creates a list called prime_sum_pairs using a nested list comprehension to generate pairs of numbers between 1 and 10 such that their sum is a prime number. Here's how the code works:

  • def is_prime(n): This line defines a function named is_prime that takes an integer n as input and returns True if n is prime and False otherwise. The function first checks if n is less than or equal to 1 and returns False in such cases. It then iterates through numbers from 2 to the square root of n and checks if n is divisible by any of those numbers. If it finds a divisor, it returns False. If no divisors are found, it returns True, indicating that n is prime.
  • prime_sum_pairs = [(x, y) for x in range(1, 11) for y in range(1, 11) if is_prime(x + y)]: This line of code initializes a variable named prime_sum_pairs and assigns it the result of a nested list comprehension.
    • for x in range(1, 11): This part of the code sets up the outer loop, which iterates through numbers from 1 to 10 (inclusive). It generates values for x.
    • for y in range(1, 11): This part sets up the inner loop, which also iterates through numbers from 1 to 10 (inclusive). It generates values for y.
    • if is_prime(x + y): This is a condition that checks whether the sum of x and y is prime by calling the is_prime function with x + y as an argument.
    • [(x, y) for x in range(1, 11) for y in range(1, 11) if is_prime(x + y)]: This is the nested list comprehension itself. It iterates through all possible pairs of numbers (x, y) from 1 to 10 and includes pairs in the new list where the sum of x and y is prime.
  • print(prime_sum_pairs): This line of code prints the prime_sum_pairs 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_sum_pairs = [(x, y) for x in range(1, 11) for y in range(1, 11) if is_prime(x + y)]
 
print(prime_sum_pairs)

Output

[(1, 1), (1, 2), (1, 4), (1, 6), (1, 10), (2, 1), (2, 3), (2, 5), (2, 9), (3, 2), (3, 4), (3, 8), (3, 10), (4, 1), (4, 3), (4, 7), (4, 9), (5, 2), (5, 6), (5, 8), (6, 1), (6, 5), (6, 7), (7, 4), (7, 6), (7, 10), (8, 3), (8, 5), (8, 9), (9, 2), (9, 4), (9, 8), (9, 10), (10, 1), (10, 3), (10, 7), (10, 9)]

Example Programs