Pairs of distinct elements and their sum of digits from two lists as a tuple in Python


This Python code processes two lists, list1 and list2, and creates a tuple of tuples named digit_sum_tuples. The tuple contains pairs of elements from the two lists and the sum of their digits. Here's how the code works:

  • list1 = [123, 456, 789]: This line initializes a variable named list1 and assigns it a list containing three integers.
  • list2 = [234, 567, 890]: This line initializes a variable named list2 and assigns it another list containing three integers.
  • digit_sum_tuples = tuple(...): This line initializes a variable named digit_sum_tuples and assigns it a tuple created by using a generator expression.
    • (... for x in list1 for y in list2): The generator expression iterates through all pairs of elements (x, y) from list1 and list2.
    • (x, y, sum(int(digit) for digit in str(x)) + sum(int(digit) for digit in str(y))): For each pair of elements (x, y), it calculates the sum of the digits in both x and y by converting them to strings, splitting the strings into digits, and summing those digits. It then creates a tuple of the form (x, y, sum_of_digits).
  • 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(digit_sum_tuples): This line of code prints the digit_sum_tuples tuple to the console.

Source Code

list1 = [123, 456, 789]
list2 = [234, 567, 890]
digit_sum_tuples = tuple((x, y, sum(int(digit) for digit in str(x)) + sum(int(digit) for digit in str(y))) for x in list1 for y in list2)
print(list1)
print(list2)
print(digit_sum_tuples)

Output

[123, 456, 789]
[234, 567, 890]
((123, 234, 15), (123, 567, 24), (123, 890, 23), (456, 234, 24), (456, 567, 33), (456, 890, 32), (789, 234, 33), (789, 567, 42), (789, 890, 41))

Example Programs