In Python, we look at a list as a data structure that is a mutable (or changeable) ordered sequence of elements. A list’s items are the elements or values that make up the list. Lists are characterized by values between square brackets [ ], just as characters between quotes define strings.
If you need to function with a large number of similar values, lists are ideal. They allow you to hold data that belongs together, condense your code, and apply the same methods and operations to multiple values simultaneously.
Consider all of the various collections you have on your computer while speaking about Python lists and other data structures that are forms of collections: your collection of files, your music playlists, your browser bookmarks, your emails, the collection of videos you can access on a streaming service, and more.
Summing a list in Python
This article seeks to illustrate how to find the sum of the elements in a list provided these elements are numbers. However, you may also wish to merge a list of strings or non-numerical values where sum() will not be helpful but we can engage other approaches as will be illustrated in the examples. There are various ways to sum a lists’ elements in Python. We hope that by the end of this article, you would have mastered at least one approach that resonates with you more.
Using sum() function
Python has an inbuilt function called sum() which aids in adding up the numbers in a list. Summing up lists is required virtually in every sphere that we interact with lists.
# program demo for the working of sum() with a list of numbers my_numbers = [1,2,3,4,5,1,4,5] #no initial value provided results = sum(my_numbers ) print(results) # initial value= 10 results = sum(my_numbers, 10) print(results)
Breakdown of the above code (the syntax):
sum(iterable, initial_val)
Iterable: It may be a dictionary, tuple, or a list of numbers
initial_val: It is usually added to the resultant sum of the iterable from left to right. However, it is set by default to 0 in case the initial value is not given.
This results in the two obvious syntaxes applied to the above piece of code.
sum (list, initial_val)
Here, the initial_val is added to the sum of the given list
sum(list)
In this case, the initial value is automatically set to 0; thus, the return value is the summation of the entirety of the items in the list.
Use math.fsum(iterable) if you need to add floating-point numbers with exact precision. For instance,
import math my_numbers = [1,2,3,4,5,1,4,5] math.fsum(my_numbers)
Example 1: sum () function
# Program to add students height to a list # creating a list of student's height students_height = [11, 5, 17, 18, 23] # use the sum() function total = sum(students_height) # print the total value print("sum of students height in a given list: ", total)
Example 2: sum () function
students_height = [5, 10, 3, 8, 5, 6, 7, 1, 9, 2] # Sum of 'students_height ' from 0 index to 9 index. sum(students_height ) == sum(students_height [0:len(students_height )] final_sum = sum(students_height [0:len(students_height )]) print(final_sum)
TypeError
What happens when non-numbers are passed to the list?
Errors will occur when non-numbers have been passed to the list. This kind of error is called the TypeError.
# Program to demonstrate TypeError exception in the function sum() arr = ["a","b","c"] # no initial value is given as a parameter result = sum(arr) print(result) # initial_val = 5 result = sum(arr, 5) print(result)
A practical application of the sum () function in a list is finding the average number of a list of numbers, as shown below.
# Program to demonstrate sum()'s practical application students_height = [1,2,3,4,5,1,4,5] # start = 10 total = sum(students_height ) average_height= total/len(students_height ) print (average_height)
sum list elements using for loop
The first two examples will traverse through the entire list using a for loop. Meanwhile, every single value is added to the total variable. As a result, the sum of the entire list is returned at the end.
Example 1: sum list elements using for loop
# Program to add elements in a list total = 0 # creating a list of student's height students_height = [11, 5, 17, 18, 23] # Iterate each element in list & add them for val in range(0, len(students_height )): total = total + students_height [val] # printing the sum of students height print("Sum of all students height in the given list: ", total)
Example 2: sum list elements using for loop
def sumList(my_list): total = 0 for val in my_list: total = total + val return total students_height = [1,3,5,2,4] print ("The sum of students list is", sumList(students_height))
Using while () loop
The approach here is similar to that of the for loop. Thus, every single value is added to the total variable and the sum of the entire list is returned at the end.
# use_while_loop.py # Program to add the elements in a list using the while() loop total = 0 val = 0 # creating a list of student's height students_height = [11, 5, 17, 18, 23] # Iterate over each element in list & add them while (val < len(students_height)): total = total + students_height[val] val += 1 # print the total value print("sum of students height in the given list: ", total)
Using Recursion
Recursion is different from the previous two approaches. Here, the function calls itself directly or indirectly. The program below, uses recursion to illustrate how to find the sum students’ height in a list.
Example 1: Using Recursion
# program to find sum students' height in a list using recursion # creating a list of student's height students_height = [11, 5, 17, 18, 23] # creating sum_list function def sumOfList(list , size): if (size == 0): return 0 else: return list[size - 1] + sumOfList(list, size - 1) # Driver code for the program total = sumOfList(students_height , len(students_height )) print("sum of students height in a given list: ", total)
Example 2: Using Recursion
def sumList(list,n): if n == 0: return list[n] return list[n] + sumList(list,n-1) students_height = [1,3,5,2,4] print ("The sum of students height is", sumList(students_height ,len(students_height)-1))
To sum it all up, we write a program that will request input from the user, then put the input in a list and output the results.
Pseudocode:
Use input () or raw_input() to read input from the user specifying the length of the list
Initialize an empty list that contains student’s height as students_list = [].
Use for loop to read each number.
Add every single height to the list in the for loop.
Use the inbuilt function sum () to add the student’s heights contained in the list.
return the result.
#request_students_height.py students_heights = [] list_count = int(input('What is the size of the list(in numbers) : ? ')) for n in range(list_count ): numbers = int(input('Enter number ')) students_heights.append(numbers) print("sum of students height :", sum(students_heights))
Sum numbers only in a list with various data types
mixed_list = ['a',1,'f',3.2,4] sum([i for i in mixed_list if isinstance(i, int) or isinstance(i, float)])
What if I want to merge a list of strings?
The sum will not work in this case. Instead, we will use join ()
list = ['a','b','c','d'] sum(list) ','.join(list) ' '.join(list)
Sum List Ignore Nan
Here we handle a case when given a list of numerical values that may contain some values that are not numbers. This is commonly referred to as nan (=” not a number”). The goal is to sum all numerical values and ignore entries with nan.
For instance, say, you’ve got the list new_list = [float(“nan”), 8, 5, float(“nan”),7, float(“nan”),11, 4] and your aim is to sum over all values that are not nan.
First, we will use list comprehension to filter the list so that only the elements that satisfy the condition – those that do not have nan- remain. Subsequently, use the sum () function to add all the remaining values.
The following example is an implementation of code that sums all values that are not nan.
# program to check isnan(x) import math # list creation new_list = [float("nan"), 8, 5, float("nan"),7, float("nan"),11, 4] # forget to ignore 'nan' print(sum(new_list)) # ignore 'nan' print(sum([x for x in new_list if not math.isnan(x)]))
Sum List Ignore None
The target case scenario is a list of numerical values that may contain some values as None. The aim is to sum all values that are not the value None.
Consider a list new_list = [None, 5, None, None, 8, None, 10, None, 2, 1, None, 3] . The expected outcome is to sum all values that are not None.
List comprehension is essential to filter the list so that only the elements that satisfy the condition are left. i.e., Those that are different from None. Subsequently, use the sum() function to add over the remaining values.
The following code adds all values in the list except those that contain None.
# list creation new_list = [None, 5, None, None, 8, None, 10, None, 2, 1, None, 3] # filter the list filtered_list = [x for x in new_list if x!=None] # sum over the filtered list resultant_sum = sum(filtered_list) # print print(resultant_sum)
Sum List Elements that meet a Condition
This section aims to test summing all values in a given list that meet a certain condition. For instance, consider the list new_list = [3, 1, 20, 8, 2, 3], and the target is to sum all values that are larger than 5.
A list comprehension is initially used to filter the list so that the elements that remain satisfy the condition. Subsequently, use the function sum() to add the remaining values.
The following code adds all the values that satisfy a certain condition (e.g., x>5).
# create the list new_list = [3, 1, 20, 8, 2, 3] # filter the list filtered_list = [x for x in new_list if x>5] # sum over the filtered list resultant_sum = sum(filtered_list) # print print(resultant_sum)
Sum List Slice
Consider an original list called original_list having the count of steps made by athletes. The intention is, to sum up, a slice of the original list between the start and the step indices. We assume that there is a given step size as well.
For instance, if the original_list is [5, 18, 1, 11, 7, 8, 3, 6]. Sum up the slice original_list[3:4:3] with start=3, stop=4, and step=3.
Slicing is used to access a section of the original list. Post that, apply the sum () function to the result.
Below is the code implementation of the sum of a given slice.
# Sum up the slice original_list[3:4:3] with start=3, stop=4, and step=3. # list creation original_list = [5, 18, 1, 11, 7, 8, 3, 6] # slice creation new_slice = original_list[3:4:3] # calculate the sum resultant_sum = sum(new_slice) # print the result print(resultant_sum)
Can you sum a List with List Comprehension?
List comprehension is a feature in Python that allows you to create a new list from an existing iterable. Unfortunately, it is not possible to sum up all values in a list using only list comprehension. Because as stated earlier, list comprehension exists to create a new list from the original list. Summing up values in a list is, however, not related to creating a new list. Instead, it is about getting rid of the list and aggregating all the list values into a single numerical value.
Sum List of Tuples Element-Wise
How do you sum up a list of tuples element-wise? For example, the list [(4, 1), (3, 0), (0, 8)]. The idea is to sum up the first two tuples so as to obtain the “summed tuple” (4+3+0, 1+0+8)=(7, 9).
First, Unpack the tuples into the zip function to combine the first and second tuple values. Subsequently, sum up those values separately. Below is the implementation of this concept.
# sum_list_of_tuples_element_wise.py # list of tuples original_list = [(4, 1), (3, 0), (0, 8)] # aggregation of the first and second tuple values resultant_zipped = original_list(zip(*original_list)) # sum values for the first and second tuple final_result = (sum(resultant_zipped [0]), sum(resultant_zipped [1])) # print the final result print(final_result)
Sum List of Lists
We are trying to figure out how to sum a list of lists such as [[1, 2], [3, 4], [5, 6]] in Python. First, use a simple for loop with a helper variable to concatenate all the lists.
The following code concatenates all lists into a single list.
# sum_list_of_lists.py # sum a list of lists list_of_lists = [[2, 1], [4, 5], [7, 9]] final_sum = [] for x in list_of_lists: final_sum.extend(x) print(final_sum)