Reputation: 25
I was trying to sum the digits for every element in the list and print the sum of every element at once but my code below only gives me 6 6 6. My desired output is 6 1 2.
#pythonCode#
my_list = [15, 10, 20]
sum = 0
m = ""
for i in range(0, 3):
while m != 0:
rem= my_list[i] % 10
m = my_list[i] //10
my_list[i] = m
sum = sum + rem
print(sum)
Upvotes: 2
Views: 77
Reputation: 14546
You could do this using map
to apply a lambda function - if I understand the desired output correctly:
>>> my_list = [15, 10, 20]
>>> list(map(lambda x: sum(int(s) for s in str(x)), my_list))
[6, 1, 2]
Written out in full, this is roughly equivalent to:
my_list = [15, 10, 20]
for integer in my_list:
total = 0
for digit in str(integer):
total += int(digit)
print(f"The sum of {integer} is {total}")
Output:
The sum of 15 is 6
The sum of 10 is 1
The sum of 20 is 2
Upvotes: 3