0

if I had a list

results = ['1','4','73','92']

how do I get that list to call on itself and add all elements together? the elements have to be strings

hailice
  • 5
  • 3
  • 1
    `sum(map(int, results))`? – j1-lee Aug 09 '22 at 03:44
  • Welcome to Stack Overflow. Please read [ask] and https://meta.stackoverflow.com/questions/261592. Before posting, try to break a problem down into logical steps. *After checking for existing duplicates*, try asking a separate, *specific* question about each part *where you are stuck*. In this case, there are three clear sub-problems: 1) how do we convert a string to an integer? 2) Once we know how to do that, how do we repeat that for all the strings, making a list of integers? 3) Now that we have that list, how do we add up the numbers? Each of these is a common duplicate. – Karl Knechtel Aug 09 '22 at 04:08

4 Answers4

2

map str to int and sum it

results = ['1','4','73','92']
sum(map(int, results))
Nawal
  • 321
  • 3
  • 7
1

You can use list comprehension to convert the list of strings to a list of ints, then use the sum function to add all of the integers up.

results = ['1','4','73','92']
sum([int(x) for x in results]) # 170
Zain Ahmed
  • 43
  • 8
0

This can be achieved using a for loop.

First, create a variable for the total:

total = 0

Next, loop through all elements in the list:

for result in results:

Then, check if the string is a number:

if result.isnumeric():

Finally, add the result to the total:

total += int(result)

This results in the final code of:

total = 0
for result in results:
    if result.isnumeric():
        total += int(result)
KingsDev
  • 654
  • 5
  • 21
0

One way to do this is using a list comprehension + sum operator:

sum([float(num) for num in results])

Note that it's safer to use float() instead of int() since your elements may include decimals.

  • `float()` has its own limitations; it will not accurately represent large integers, and floating-point values [aren't actually decimal](https://stackoverflow.com/questions/588004). – Karl Knechtel Aug 09 '22 at 04:10
  • Thanks for pointing that out, good to know the details. However, in this use case, float will almost always do better than int. – Dina Kisselev Aug 09 '22 at 04:11