In this short tutorial, we look at how we can use Python to find the sum()
of a list. We look at the various methods to do this along with their limitations.
This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.
Table of Contents - Python Sum List
- Using Sum to find the sum of a List
- How to use the sum() function?
- Limitation and Caverts - Python Sum List
Python Sum List:
While using Python, there are sure to be numerous use cases where you might have to calculate the sum of an iterable. For the purpose of this blog, we mainly focus on lists; however, the same method can be applied to other iterables as well.
An example of a use case is the use of sum()
to return the sum of a list that contains the weekly income of employees to calculate monthly income.
How to use the sum()
function?
The sum()
function returns the sum of an iterable. Sum()
takes a list (iterable) and returns the sum of the numbers within the list.
The syntax is as follows:
sum(iterable, start)
Parameters:
-
Iterable
- Required, iterable can be a list, tuples, and dictionary -
Start
- Optional, if passed it the value will be added returned sum
Code and Explanation:
#Using range to create list of numbers
numbers = list(range(0,10))
sum_numbers = sum(numbers)
print(sum_numbers)
#Output - 45
#Passing an argument as start
sum_numbers = sum(numbers, 10)
print(sum_numbers)
#Output - 55
As seen in the above code snippet, the sum()
function is used to add the values in the range that has been specified. You can similarly use the function for various operations.
Limitation and Caveats - Python Sum List
A common error that arises while using the sum()
function, is when the list contains a string. Since it is not possible to add int values in strings, Python returns a TypeError
. Let us look at such an instance.
#Creating a list of number and a string
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "10"]
sum_numbers = sum(numbers)
print(sum_numbers)
Python returns this output:
Traceback (most recent call last):
File "C:\Users\Python\Using_sum.py", line 4, in <module>
sum_numbers = sum(numbers)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
As explained, the int value in the string causes the TypeError
. Other than this limitation, you can make use of the sum()
function in Python with ease for all summing operations.
Top comments (3)
Before using the
sum
function to summarize the list, we can consider using themap
to try to cast all values tointeger
type firstly.For example, the sample codes are as follows:
Great article! Looking forward to more from you!
Thank you. :)