Generate a list of tuples containing two numbers whose sum is even


This Python code creates a list called even_sum_tuples using a nested list comprehension to generate tuples of pairs of numbers between 1 and 10 whose sum is even. Here's how the code works:

  • even_sum_tuples = [(x, y) for x in range(1, 11) for y in range(1, 11) if (x + y) % 2 == 0]: This line of code initializes a variable named even_sum_tuples and assigns it the result of a 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 (x + y) % 2 == 0: This is a condition that checks whether the sum of x and y is even. If the sum is even (i.e., the remainder when divided by 2 is 0), it proceeds to the next part.
    • [(x, y) for x in range(1, 11) for y in range(1, 11) if (x + y) % 2 == 0]: This is the 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 even.
  • print(even_sum_tuples): This line of code prints the even_sum_tuples list to the console.

Source Code

even_sum_tuples = [(x, y) for x in range(1, 11) for y in range(1, 11) if (x + y) % 2 == 0]
print(even_sum_tuples)

Output

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

Example Programs