While working with the Python programming language, users create various kinds of data structures, such as lists, dictionaries, tuples, and many more. These are also known as iterable and are used to store the elements of different data types. Users can perform various kinds of operations on the iterable elements, such as calculating the sum of their elements, sorting the elements of the iterable, and many more. Python provides various predefined functions to perform such operations.
This guide will exemplify various cases of using the “sum()” function in Python.
Quick Outline
- What is Python’s “sum()” Function?
- How to Utilize Python’s “sum()” Function?
- How Errors and Exceptions Occur While Utilizing Python’s “sum()” Function?
- How to Find the Sum of Iterable Elements Without Using Python’s “sum()” Function?
What is Python’s “sum()” Function?
The “sum” function is a built-in Python function that calculates the sum of given iterable elements. The iterable can be a list, set, dictionary, tuple, range, etc with elements of different data types.
Syntax
The syntax of the “sum()” function is:
sum(<iterable>, <start>)
Parameter
The “sum()” function takes two parameters i.e. “iterable” and “start”.
- “iterable” is a required parameter. It can be a list, dictionary, tuple, or set containing numbers only.
- “start” is an optional parameter. It is the value(number) that is added to the specified numbers’ sum in the iterable. Its default value is zero.
Return Value
The “sum()” function returns the total sum of all the elements/items existing in the iterable(list, dictionary, tuple, etc).
How to Utilize Python’s “sum()” Function?
To use the “sum()” function in Python, pass the desired list, dictionary, tuple, set, etc. as an argument to it and it will return the sum of their elements or items. We have listed down some common use cases of the “sum()” function in Python:
- Case 1: Use the “sum()” Function on a List
- Case 2: Use the “sum()” Function on a Dictionary
- Case 3: Use the “sum()” Function on a Tuple
- Case 4: Use the “sum()” Function on a Set
- Case 5: Use the “sum()” Function on a Range
Case 1: Use the “sum()” Function on a List
A list is a data structure in Python that is utilized to store the collection of data including integers, strings, floats, tuples, etc. Users can find the sum of all the list elements using the “sum()” function. Check out the provided examples to see how to use the “sum()” function on various kinds of lists:
Example 1: Sum of Integer List
In this example, we are creating an integer list named “int_list” with simple numeric values and passing it to the “sum()” function. Then, we print the results to view the sum:
int_list = [2, 4, 6, 8]
Sum_list1 = sum(int_list)
print('Sum of Integer List: ', Sum_list1)
The below output displays the sum of the integer list’s elements:
Users can also use the “start” parameter with the “sum()” function to provide the start value. For instance, we are specifying the start value “10” in the same above code to see the difference. The addition will start from the number “10” and all the list items will be added to it:
int_list = [2, 4, 6, 8]
Sum_list1 = sum(int_list, start=10)
print('Sum of Integer List: ', Sum_list1)
It can be observed that the sum value of the integer list has been added to “10”:
Example 2: Sum of Float List
In this example, we are creating and passing a “float_list” list containing float values to the “sum()” function:
float_list = [1.4, 3.5, 6.1, 7.2]
Sum_list2 = sum(float_list)
print('Sum of Float List: ', Sum_list2)
The “sum()” function has added all the float values of the list and displays the result:
Example 3: Sum of Complex Numbers List
Here, we are creating a list with complex numbers named “comNum_list” and passing it to the “sum()” function:
comNum_list = [1 + 2j, 3 + 4j]
Sum_list3 = sum(comNum_list)
print('Sum of Complex Numbers List: ', Sum_list3)
The above code returns the sum of the complex numbers list as seen below:
Example 4: Sum of Mixed List
In this example, we have a “mixed_list” list with mixed data types containing float numbers, and positive and negative integers. We are passing it to the “sum()” function to calculate the sum of its all elements:
mixed_list = [6, -1, 4.1, 3.7, 5, 2.9]
Sum_list4 = sum(mixed_list)
print('Sum of List: ', Sum_list4)
The below output shows the sum of all the mixed list’s elements:
Case 2: Use the “sum()” Function on a Dictionary
A dictionary is just like a list but it stores the desired data in a key-value pair format. It contains pairs of keys and their corresponding values of any data type. The “sum()” function can be used on a dictionary to add the values of dictionary keys. Look at the following example to see how to find the sum of dictionary values with different data types.
Example 1: Sum of Integer Dictionary
In this example, we have a dictionary named “int_dict” with integer values. We are passing this integer dictionary to the “sum()” function with the collaboration of the “values()” function to find the sum of its values:
int_dict = {'a': 5, 'b': 10, 'c': 15}
Sum_dict1 = sum(int_dict.values())
print('Sum of Integer Dictionary: ', Sum_dict1)
The “sum()” function has successfully calculated the sum of the numeric values of the dictionary:
Example 2: Sum of Float Dictionary
In this case, we will use the “sum()” function on the “float_dict” dictionary to calculate the sum of its floating point values:
float_dict = {'a': 1.3, 'b': 5.2, 'c': 6.4}
Sum_dict2 = sum(float_dict.values())
print('Sum of Float Dictionary: ', Sum_dict2)
In the below output, the sum of the dictionary’s float values can be seen:
Example 3: Sum of Mixed Dictionary
In this example, we have a mixed dictionary with integer and float numbers. We are using the “sum()” function on it to add its all values:
mixed_dict = {'a': 3, 'b': 8.2, 'c': 5.7}
Sum_dict3 = sum(mixed_dict.values())
print('Sum of Float Dictionary: ', Sum_dict3)
This has added all the values of the mixed dictionary as seen below:
Case 3: Use the “sum()” Function on a Tuple
In Python, a tuple is also like a list that stores data of various types but its elements are immutable. The tuple elements cannot be changed once it is created. Users can find the sum of all the tuple elements using the “sum()” function.
For example, we have a tuple named “tuple1” that contains positive and negative integers and floating numbers. We will pass it to the “sum()” function to get the sum of its all values:
tuple1 = (6, 5.7, -1, 4.9)
Sum_tuple = sum(tuple1)
print('Sum of Tuple: ', Sum_tuple)
The below output displays the sum of the tuple’s elements:
Case 4: Use the “sum()” Function on a Set
A Set is also a data structure that is utilized to store the unique values of different data types. It can have integer, float, strings, and boolean values. The “sum()” function can also be used on a set to add its elements.
For instance, we have a “set1” set with different data types’ elements. We are using the “sum()” function on it to calculate the sum of its all elements:
set1 = {2, 4.7, -9, 5.1, 8}
Sum_set = sum(set1)
print('Sum of Set: ', Sum_set)
The above code has returned the sum of all the set’s elements as seen below:
Case 5: Use the “sum()” Function on a Range
A range is a sequence of specific numbers. Users can generate a desired series of numbers and also find their sum. They can use the “sum()” function to find the sum of range elements.
Here, we have created a “myRange” range from “1” to “9” using the “range()” function. Then, we have passed the range to the “sum()” function to calculate the sum of its elements:
myRange = range(1, 10)
Sum_range = sum(myRange)
print('Sum of Range: ', Sum_range)
In the below screenshot, the sum of the range’s elements can be seen:
How Errors and Exceptions Occur While Utilizing Python’s “sum()” Function?
As we know the “sum()” function takes the iterable that contains numbers only. Therefore, if a user passes any list, dictionary, or tuple containing strings or anything other than the number to the “sum()” function, it will throw an error called “TypeError”.
Check out the provided examples to see how this error occurs while using the “sum()” function in Python.
Example 1: Passing List of Strings to the “sum()” Function
In this example, we are passing a “list1” list containing a string element to the “sum()” function:
list1 = ['hello']
Sum_list = sum(list1)
print('Sum of the List: ', Sum_list)
In the below output, the “TypeError” can be seen that occurred because of the string list:
Example 2: Passing Dictionary Containing Strings to the “sum()” Function
In this example, we will pass a “dict1” dictionary that contains integers and string values to the “sum()” function:
dict1 = {'key1': 10, 'key2': 'bye', 'key3': 'python'}
Sum_dict = sum(dict1.values())
print('Sum of the Dictionary: ', Sum_dict)
As you can see, passing the string values to the “sum()” function has raised the “TypeError” as seen below:
How to Find the Sum of Iterable Elements Without Using Python’s “sum()” Function?
Python enables users to calculate the sum of iterable elements without using the “sum()” function. Users can use the “for” loop or recursion to perform a sum operation on iterable elements.
Method 1: Find Sum of Iterable Elements Using “for” Loop
The “for” loop is utilized to iterate over an iterable. It can be used to find the sum of the iterable elements including lists, dictionaries, etc.
For example, we have defined an integer list “list1” to calculate the sum of its elements. The “sum” variable is initialized to store the sum. The “for” loop will iterate through the “list1” list and add each element to the “sum” variable. The “print()” function will finally print the sum of all list elements:
list1 = [2, 4, 6, 8]
sum = 0
for i in list1:
sum += i
print('Sum of List Elements: ', sum)
The below output displays the sum of the list elements:
Method 2: Find the Sum of Iterable Elements Using Recursion
The recursion function is a specific function that calls itself. This is also an alternative way to calculate the sum of iterable elements in Python.
For example, we have declared the function “total()” that takes a list of numbers as an argument and returns the sum of all the elements in the list. This function uses recursion to iterate over the list and add each element to the result of the previous call. If the list is empty, the function will return “0” otherwise it will calculate and return the sum of list elements. The “print()” function will finally display the sum of the list elements:
def total(num):
if len(num) == 0:
return 0
return num[0] + total(num[1:])
print(total([2, 4, 6, 8]))
It can be observed that the sum of list elements has been successfully calculated using recursion:
Note: Click on the provided link to access Google Colab Notebook.
Conclusion
In Python, the built-in “sum()” function calculates the sum of the provided iterable elements including lists, dictionaries, sets, etc. To use the “sum()” function in Python, pass the desired list, dictionary, tuple, or set as an argument to it and it will return the sum of their elements or items. This guide has exemplified all the ways to use the “sum()” function in Python.