Pairs of distinct elements and their sum of digits, using divmod(), from two lists as a tuple in Python


This Python code combines two lists, list1 and list2, and then creates a tuple named digit_sum_tuples containing unique pairs of elements from both lists. Each pair consists of one element from list1 and one element from list2, along with the sum of their digit sums (sums of individual 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(set((x, y, sum(divmod(x, 10)) + sum(divmod(y, 10))) for x in list1 for y in list2)): This line initializes a variable named digit_sum_tuples and assigns it a tuple created using a generator expression.
    • for x in list1 for y in list2: This part of the code sets up nested loops, iterating through elements in list1 (x) and elements in list2 (y).
    • (x, y, sum(divmod(x, 10)) + sum(divmod(y, 10)): For each pair of elements (x, y), this part creates a tuple containing x, y, and the sum of their digit sums.
      • divmod(x, 10): This function calculates the quotient and remainder when x is divided by 10. It effectively breaks down the number x into its individual digits.
      • sum(...): This function calculates the sum of the digits obtained from divmod(x, 10) and divmod(y, 10).
    • set(...): This part converts the generated tuples into a set, removing any duplicate tuples.
    • tuple(...): This surrounds the set and converts it back 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(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(set((x, y, sum(divmod(x, 10)) + sum(divmod(y, 10))) 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, 42), (456, 890, 140), (789, 890, 176), (456, 567, 114), (456, 234, 78), (123, 890, 104), (123, 567, 78), (789, 234, 114), (789, 567, 150))

Example Programs