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


This Python code processes two lists, list1 and list2, and creates a tuple called product_tuples. Each element in this tuple is a triple containing two numbers from the lists and their product (multiplication result). 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.
  • product_tuples = tuple((x, y, x * y) for x in list1 for y in list2): This line initializes a variable named product_tuples and assigns it a tuple created using a nested generator expression.
    • for x in list1: The outer loop iterates through each number x in the list1.
    • for y in list2: The inner loop iterates through each number y in the list2.
    • (x, y, x * y): For each combination of x and y, it creates a triple that consists of the two original numbers and their product, which is computed as x * y.
    • tuple(...): This surrounds the nested generator expression and converts the generated triples 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(product_tuples): This line of code prints the product_tuples tuple (which contains triples of numbers and their products) to the console.

Source Code

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

Output

[1, 2, 3]
[4, 5, 6]
((1, 4, 4), (1, 5, 5), (1, 6, 6), (2, 4, 8), (2, 5, 10), (2, 6, 12), (3, 4, 12), (3, 5, 15), (3, 6, 18))

Example Programs