Python | Sum of number digits in List


When it is required to sum the number of digits in a list, a simple loop and the ‘str’ method can be used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

The ‘str’ method converts the given value into a string data type.

Below is a demonstration for the same −

Example

 Live Demo

my_list = [11, 23, 41, 62, 89, 0, 10]
print("The list is : ")
print(my_list)
my_result = []
for elem in my_list:
   sum_val = 0
   for digit in str(elem):
      sum_val += int(digit)
   my_result.append(sum_val)
print ("The result after adding the digits is : " )
print(my_result)

Output

The list is :
[11, 23, 41, 62, 89, 0, 10]
The result after adding the digits is :
[2, 5, 5, 8, 17, 0, 1]

Explanation

  • A list is defined, and is displayed on the console.
  • Another empty list is created.
  • The list is iterated over, and every element in the list is converted to a string, and iterated over.
  • It is then added and converted as a single digit.
  • This is done on all elements of the list.
  • This is appended to the empty list.
  • It is then displayed as output on the console.

Updated on: 11-Mar-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements