How to Find Sum of Elements in List Python [5 Best Examples]

How to Find Sum of Elements in List Python [5 Best Examples] - linuxnasa

In this tutorial, we will learn about how to find sum of elements in List Python using 5 best examples. In Python, List allows various operations like, adding elements, searching element, deleting elements, list comparison and so on. One of the basic and widely used operation is adding elements of a List to find the total value. This is one of the vital List operation  specially when we deal with large data set. We will learn about finding the total of all elements in a List using various ways in the upcoming section of this tutorial. So let’s get started.

 

Python List Overview

In Python, List is a versatile data structure which is widely used by Python developers. List allows to store collection of items either of same data type(like int) or different data type(like int, string, float, list). List is mutable which means once you create a list, you can modify its elements(add, remove or change elements). List is defined using ‘[]’ bracket and elements are inserted withing this bracket.

 

How to Find Sum of Elements in List Python [5 Best Examples]

There are various ways to calculate the sum of elements in a list. We will see which all built-in modules are available in Python which can be utilized to find the elements sum in a list.

Also Read: How to Install python-socketio Stable Diffusion [5 Easy Steps]

Example-1: Using ‘sum()’ Function

In Python, sum() is a built-in function that takes an iterable of numbers as its argument and returns the total sum of all those numbers. The syntax of sum() function is given below followed by a code where we have defined a list which hold certain number of integer type elements.

We have also imported the module ‘time’ which can be used to find the total execution time taken to calculate the sum in a list. we have set the timer at the beginning of code using ‘time.time()’ function. After completing the execution to calculate the sum, we have again set the timer after the completion of logic to find the elements sum in list. The difference between two timer will return the processing(execution) time taken by the code.

Syntax

sum(iterable, start=o)

 

Code using sum() function

import time
num_list = [2,5,3,8,6]

start_time = time.time()

sum = sum(num_list)
print(f"Sum of all List Elements Using built-in sum() function: {sum}")

end_time = time.time()

total_time = (end_time - start_time)
print(f"Processing took: {total_time:.6f}s")

OUTPUT

Sum of all List Elements Using built-in sum() function: 24
Processing took: 0.000027s

 

Example-2: Using List Comprehension

In Python, list comprehension is a technique used to create lists in more concise and readable way. It helps to write short code to create a list by applying an expression to each element in an existing iterable and optionally filtering the elements based on a condition. We will modify the above code to use the List comprehension technique to find the sum of elements in defined list. We will notice that it returns the same output as shown below.

Syntax

new_list = [expression for item in iterable if condition]

 

Code using List comprehension

import time
num_list = [2,5,3,8,6]

start_time = time.time()

sum = sum([x for x in num_list])
print(f"Sum of all List Elements Using List comprehension: {sum}")

end_time = time.time()

total_time = (end_time - start_time)
print(f"Processing took: {total_time:.6f}s")

OUTPUT

Sum of all List Elements Using List comprehension: 24
Processing took: 0.000030s

 

Example-3: Using ‘reduce()’ Function

In Python, ‘functools.reduce()’ function is a higher order function that is used to apply a particular function in a cumulative way to the items of an iterable, reducing the iterable to a single output. Let us again modify the same code to use the reduce method to find the sum of elements in defined list. Save and execute below code.

Syntax

functools.reduce(function, iterable[, initializer])

 

Code using reduce() function

import time
from functools import reduce
num_list = [2,5,3,8,6]

start_time = time.time()

sum = reduce(lambda x, y: x + y, num_list)
print(f"Sum of all List Elements Using reduce() function: {sum}")

end_time = time.time()

total_time = (end_time - start_time)
print(f"Processing took: {total_time:.6f}s")

OUTPUT

Sum of all List Elements Using reduce() function: 24
Processing took: 0.000044s

 

Example-4: Using ‘numpy’ Module

In Python, ‘numpy’ is very powerful module and used by developers mostly for numerical and mathematical operations. It provides support for large, multi-dimensional arrays and matrices along with a collection of high-level mathematical functions to operate on these arrays. We will calculate the sum of list elements using sum() function which is provided by numpy module as shown below. Save and execute the below code. It will return the same output as returned by all other examples previously.

Code using numpy module

import time
import numpy as np
num_list = [2,5,3,8,6]

start_time = time.time()

sum = np.sum(num_list)
print(f"Sum of all List Elements Using numpy Module: {sum}")

end_time = time.time()

total_time = (end_time - start_time)
print(f"Processing took: {total_time:.6f}s")

OUTPUT

Sum of all List Elements Using numpy Module: 24
Processing took: 0.000081s

 

Example-5: Using for Loop

In Python, for loop is used to iterate over iterable and do certain operation like, add elements, compare elements or any other supported operation. This is the most common and layman approach to find the summation of list elements as the processing time will be comparatively high. If we have thousands of elements in a list, execution time will be high so this approach is not suggested to used as optimized ways are already available as discussed in above examples.

Syntax

for variable in sequence:
#code to be executed

 

Code using for loop

import time

num_list = [2,5,3,8,6]
start_time = time.time()
sum = 0

for num in num_list:
    sum += num

print(f"Sum of all List Elements Using for loop: {sum}")
end_time = time.time()
total_time = (end_time - start_time)
print(f"Processing took: {total_time:.6f}s")
OUTPUT
Sum of all List Elements Using for loop: 24
Processing took: 0.000036s

 

Summary

We have discussed various ways to find the summation of elements in a given list. You can learn more about Pythons’ list operations and usage from its official document available at python.org.

Leave a Comment