python how to add all elements of a list together

Question:

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

Asked By: hailice

||

Answers:

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
Answered By: Zain Ahmed

map str to int and sum it

results = ['1','4','73','92']
sum(map(int, results))
Answered By: Nawal

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)
Answered By: KingsMMA

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.

Answered By: Dina Kisselev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.