Signup/Sign In
PUBLISHED ON: JUNE 30, 2021

Python program to find sum of elements in list

In this tutorial, we will learn to execute a program to print the sum of elements in a list in Python. For a given list with integer values, our program will return the sum of all the elements in the list. For example,

Input: [6, 8, 12, 5, 3, 10]

Output: 44

Approach To Find Sum of List Elements

For calculating the sum of a list, we can either access each sum and calculate the sum or we can use a built-in function sum() to calculate the sum of all elements.

We can follow a similar approach of calculating the sum of elements in an array for finding the sum of the list.

Approach 1: By Using Loop

In this approach, we will use a loop for accessing each element of the list and adding the elements individually.

Algorithm

Step 1- Define a function to calculate sum

Step 2- Declare a variable for storing sum

Step 3- Run a loop to access each element

Step 4- Add the element to sum

Step 5- Return sum

Step 6- Initialise list

Step 7- Call function to calculate sum

Step 8- Print vale returned by function

Python Program 1

Look at the program to understand the implementation of the above-mentioned approach.

# sum of elements

def sumlist(list):
    sum=0
    for i in range(len(list)):
        sum = sum+list[i]
    return sum

#initialise list
list = [10, 9, 7, 5]
print(list)
print("sum of list: ",sumlist(list))


[10, 9, 7, 5]
sum of list: 31

Approach 2: Using sum()

In this approach, we will use a built-in function called sum() which will calculate the sum of all the elements in an array and return the result.

Algorithm

Step 1- Initialise list

Step 2- Print

Step 3- Call sum()

Step 4- Print vale returned by sum()

Python Program 2

Look at the program to understand the implementation of the above-mentioned approach.

# sum of elements

#initialise list
list = [12, 8, 9, 2, 5]
print(list)
print("sum of list: ",sum(list))


[12, 8, 9, 2, 5]
sum of list: 36

Conclusion

In this tutorial, we have learned, two approaches by which we can calculate the sum of all the elements in a list. One, by using a loop to add the elements. Second, by using a predefined function sum() in the Python Library.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.