How to Find the Sum of a List of Integer Strings in Python?

In Python, you can get the sum of all integers in a list by using the sum method:

sum = sum([1, 2, 3, 4, 5])
print(sum) # 15

However, this does not work on a list of integer strings:

# TypeError: unsupported operand type(s) for +: 'int' and 'str'
sum(['1', '2', '3', '4', '5'])

Therefore, to calculate the sum of a list of integer strings, you can do either of the following:

Converting Integers Using map() Before sum()

You can use the map() method to convert each item in a list to an integer before calling the sum() method, for example, like so:

sum(map(int, numbers))

This can be used in the following way:

def list_sum(numbers):
    return sum(map(int, numbers))

print(list_sum(['1', '2', '3', '4', '5'])) # 15
print(list_sum([1, '2', 3, '4', 5])) # 15
print(list_sum([1, 2, 3, 4, 5])) # 15

print(list_sum(['1', '-2', '3', '-4', '5'])) # 3

print(list_sum([])) # 0

When a non-numeric value is encountered, this function would throw an error.

Converting Integers Using List Comprehension Before sum()

List comprehensions provide a short syntax to create a new list, where the result of some operation can be applied to each element of an existing list. You can use this to convert each member of an existing list to an integer and add the result to a new list. This can be done using the following code:

sum(int(num) for num in numbers)

This can be used in the following way:

def list_sum(numbers):
    return sum(int(num) for num in numbers)

print(list_sum(['1', '2', '3', '4', '5'])) # 15
print(list_sum([1, '2', 3, '4', 5])) # 15
print(list_sum([1, 2, 3, 4, 5])) # 15

print(list_sum(['1', '-2', '3', '-4', '5'])) # 3

print(list_sum([])) # 0

When a non-numeric value is encountered, this function would throw an error.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.