Reputation:
I have a list of integers stored as strings and would like to convert it and get its total in integer and they print the total.
What is the easiest way to do that?
The list is as follow:
string_numbers = ['55','63','43','44']
I want to create it in a for-loop.
thanks
Upvotes: 0
Views: 63
Reputation: 4606
Using list comprehension
print(sum([int(i) for i in string_numbers]))
# 205
Using functools.reduce
from functools import reduce
print(reduce(lambda x, y: int(x) + int(y), string_numbers))
# 205
Expanded loop:
total = []
for i in string_numbers:
total.append(int(i))
print(sum(total))
Upvotes: 0
Reputation: 23064
You can use the builtin functions sum
and map
.
Map is a functional equivalent of a for loop.
>>> string_numbers = ['55','63','43','44']
>>> sum(map(int, string_numbers))
205
You can also use a generator expression instead of map
.
>>> sum(int(n) for n in string_numbers)
Upvotes: 1
Reputation: 747
There you go:
string_numbers = ['55','63','43','44']
total = 0
for item in string_numbers:
total = total + int(item)
print(total)
Upvotes: 4