user1204906
user1204906

Reputation:

converting list of strings and getting the total as integer

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

Answers (3)

vash_the_stampede
vash_the_stampede

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

Håken Lid
Håken Lid

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

Jan
Jan

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

Related Questions