Skip to content

Write a Python function to sum all the numbers in a list | Code

Use a loop with a variable to sum all the numbers in a list in Python. Another option is to use the sum() function.

Python function to sum all the numbers in a list example

Simple example code using for loop, to sum up of a number of the given list.

num = [1, 2, 3, 4, 5]
total = 0
for x in num:
    total += x

print(total)

Output:

Write a Python function to sum all the numbers in a list

Using sum() method

a = [1, 2, 3, 4, 5]
res = sum(a)

print(res)

Output: 15

Using while() loop

total = 0
ele = 0

list1 = [11, 5, 17, 18, 23]

while ele < len(list1):
    total = total + list1[ele]
    ele += 1

print(total)

Output: 74

Recursive way

list1 = [11, 5, 17, 18, 23]


def sumOfList(lst, size):
    if size == 0:
        return 0
    else:
        return lst[size - 1] + sumOfList(lst, size - 1)


# Driver code
total = sumOfList(list1, len(list1))

print(total)

Output: 74

Do comment if you have any doubts or suggestions on this Python sum topic

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

1 thought on “Write a Python function to sum all the numbers in a list | Code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading