Generate a list of tuples containing numbers and their squares if the number is prime


This Python code defines a function is_prime(n) that checks whether a given number n is prime or not. Then, it uses a list comprehension to generate pairs of prime numbers and their squares within a specified range. Here's how the code works:

  • def is_prime(n): This line defines a function named is_prime that takes a single argument n and returns True if n is prime and False otherwise.
    • if n <= 1:: This line checks if n is less than or equal to 1. If it is, the function immediately returns False because 1 and all negative numbers are not prime by definition.
    • for i in range(2, int(n**0.5) + 1): This line sets up a loop that iterates through the numbers from 2 up to the square root of n (inclusive).
    • if n % i == 0:: Inside the loop, it checks if n is divisible by i (i.e., if n modulo i equals 0). If it is, the function immediately returns False because n is not prime if it has a divisor other than 1 and itself.
    • If the loop completes without finding any divisors other than 1 and n, the function returns True, indicating that n is prime.
  • prime_num_squares = [(x, x**2) for x in range(1, 11) if is_prime(x)] : This line of code initializes a variable named prime_num_squares and assigns it the result of a list comprehension.
    • for x in range(1, 11): This part sets up a loop that iterates through numbers from 1 to 10 (inclusive). It generates values for x.
    • (x, x**2): For each value of x, this expression creates a tuple containing two elements: the original value x and its square, calculated as x**2.
    • if is_prime(x): This condition checks if the current value of x is prime by calling the is_prime function. If x is prime, the pair (x, x^2) is included in the new list.
  • print(prime_num_squares): This line of code prints the prime_num_squares 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_num_squares = [(x, x**2) for x in range(1, 11) if is_prime(x)]
print(prime_num_squares)

Output

[(2, 4), (3, 9), (5, 25), (7, 49)]

Example Programs