Tuple of pairs of numbers and their sum from two lists in Python


This Python code creates a tuple called sum_tuples, which contains triplets of elements from list1, list2, and their sums. Here's how the code works:

  • list1 = [1, 2, 3]: This line initializes a variable named list1 and assigns it a list containing three numbers.
  • list2 = [4, 5, 6]: This line initializes a variable named list2 and assigns it a list containing three numbers.
  • sum_tuples = tuple((x, y, x + y) for x in list1 for y in list2) : This line of code initializes a variable named sum_tuples and assigns it a tuple created using a generator expression.
    • for x in list1: This part of the code sets up a nested loop that iterates through each number x in list1.
    • for y in list2: For each x from list1, it sets up another nested loop that iterates through each number y in list2.
    • (x, y, x + y): For each pair of x and y, it creates a triplet containing x, y, and their sum x + y.
    • tuple(...): This surrounds the generator expression and converts the generated triplets into a tuple.
  • 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(sum_tuples): This line of code prints the sum_tuples tuple (which contains triplets of elements and their sums) to the console.

Source Code

list1 = [1, 2, 3]
list2 = [4, 5, 6]
sum_tuples = tuple((x, y, x + y) for x in list1 for y in list2)
print(list1)
print(list2)
print(sum_tuples)

Output

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

Example Programs