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
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
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
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)
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.