How to Calculate the Sum of a List in Python


If you need to calculate and get the sum of a list in Python, then you can do the following.

Option 1 – Using sum()

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
listSum = sum(myList)
print(f"Sum of list -> {listSum}")

If you get a TypeError then you can do the following:

myList = ["1", "3", "5", "7", "9"]
myNewList = [int(string) for string in myList]
sum1 = sum(myNewList)
sum2 = sum(number for number in myNewList)
print(f"Sum of list -> {sum1}")
print(f"Sum of list -> {sum2}")

Option 2 – Using for

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
length = len(myList)
listSum = 0

for i in range(length):
    listSum += myList[i]

print(f"Sum of list -> {listSum}")