Python Forum

Full Version: How to separate the values in an element to add them
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings,

I have a python question.. I have a list with the following four elements.
What I want to do is add the vales in element 1 (17,21,29,35,36) to get the sum (138)
The area I am having the problem is how add the numbers in that element?
The numbers are all part of element 1, how would I separate them in to integers so I can add them to get the sum?

Here is an example of a list.
['01/21/2023', '17,21,29,35,36', '1,E','37.43']

Any help or guidance would be greatly appreciated.

Regards,
Monty
This would be one way:

the_list = ['01/21/2023', '17,21,29,35,36', '1,E', '37.43']

numbers = the_list[1].split(',')
total = 0

for number in numbers:
    total += int(number)

print(total)
Or, you could do that directly:

the_list = ['01/21/2023', '17,21,29,35,36', '1,E', '37.43']
total = 0
for number in the_list[1].split(','):
    total += int(number)
print(total)
Wow!! Thank you Rob101! I spent a week trying to figure this out.. I was close.
I was using the split but I was getting the comma between each value..
(Jan-23-2023, 01:04 AM)monty024 Wrote: [ -> ]Wow!! Thank you Rob101!

You're welcome; pleased to help.

Yet another way, I just thought of:
the_list = ['01/21/2023', '17,21,29,35,36', '1,E', '37.43']

int_numbers = []
for number in the_list[1].split(','):
    int_numbers.append(int(number))

print(sum(int_numbers))
Edit to add: it depends on what you want to do with the numbers. If you want to use them later on, then maybe use my 3rd way, as you'll have a list object that holds said numbers, but if all you want is the total, then there's little point in creating an object to hold them.
Lots of ways to do this. Here are a 3 more.
from functools import reduce

values = '1,2,3,4,5'

print(sum(int(n) for n in values.split(',')))
print(sum(map(int, values.split(','))))
print(reduce(lambda a, b: a + int(b), values.split(','), 0))
I presented the choices in my order of preference. Comprehensions are very useful and something you need to know how to use. map() is like a one-trick-pony version of a comprehension. I don't find reduce() very useful.