Tuple of sums of digits in numbers in Python


This Python code creates a tuple called digit_sums, which contains the sum of digits for each number in the numbers list. Here's how the code works:

  • numbers = [123, 456, 789]: This line initializes a variable named numbers and assigns it a list containing three numbers.
  • digit_sums = tuple(sum(int(digit) for digit in str(num)) for num in numbers): This line of code initializes a variable named digit_sums and assigns it a tuple created using a generator expression.
    • for num in numbers: This part of the code sets up a loop that iterates through each number num in the numbers list.
    • str(num): It converts each number to a string using str(num) so that we can work with individual digits.
    • for digit in str(num): Within the loop, it sets up a nested loop that iterates through each digit digit in the string representation of the number.
    • int(digit): For each digit, it converts it back to an integer using int(digit) so that we can sum them.
    • sum(...): This calculates the sum of the digits for each number.
    • tuple(...): This surrounds the generator expression and converts the generated sums into a tuple.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(digit_sums): This line of code prints the digit_sums tuple (which contains the sum of digits for each number in the list) to the console.

Source Code

numbers = [123, 456, 789]
digit_sums = tuple(sum(int(digit) for digit in str(num)) for num in numbers)
print(numbers)
print(digit_sums)

Output

[123, 456, 789]
(6, 15, 24)

Example Programs