Pairs of numbers and their sum, with even and odd pairs separated, from two lists as a tuple in Python


This Python code processes two lists, list1 and list2, and creates a tuple of tuples named even_odd_sum_tuples. The tuple contains two inner tuples: one for even sums and one for odd sums of pairs of elements from the two lists. Here's how the code works:

  • list1 = [1, 2, 3]: This line initializes a variable named list1 and assigns it a list containing three integers.
  • list2 = [4, 5, 6]: This line initializes a variable named list2 and assigns it another list containing three integers.
  • even_odd_sum_tuples = (..., ...): This line initializes a variable named even_odd_sum_tuples and assigns it a tuple containing two inner tuples.
    • tuple((x, y, x + y) for x in list1 for y in list2 if (x + y) % 2 == 0): The first inner tuple contains pairs of elements from list1 and list2 (x, y) where the sum (x + y) is even. It uses a generator expression to create tuples of the form (x, y, x + y) for even sums.
    • tuple((x, y, x + y) for x in list1 for y in list2 if (x + y) % 2 != 0): The second inner tuple is similar to the first, but it includes pairs where the sum (x + y) is odd.
  • print(list1): This line of code prints the original list1 to the console.
  • print(list2): This line of code prints the original list2 to the console.
  • print(even_odd_sum_tuples): This line of code prints the even_odd_sum_tuples tuple to the console.

Source Code

list1 = [1, 2, 3]
list2 = [4, 5, 6]
even_odd_sum_tuples = (tuple((x, y, x + y) for x in list1 for y in list2 if (x + y) % 2 == 0),tuple((x, y, x + y) for x in list1 for y in list2 if (x + y) % 2 != 0))
print(list1)
print(list2)
print(even_odd_sum_tuples)

Output

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

Example Programs