Skip to content

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}")
Code language: Python (python)

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}")
Code language: Python (python)

Option 2 – Using for

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] length = len(myList) listSum = for i in range(length): listSum += myList[i] print(f"Sum of list -> {listSum}")
Code language: Python (python)

See also  Count and Say with Python
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x