How to use Python to sum a list?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.
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
- Other Related Concepts
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 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:
- 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:
As seen in the above code snippet, the
#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
sum()function is used to add the values in the range that has been specified. You can similarly use the function for various operations.
Limitations and Caveats - Python Sum ListA 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.
Python returns this output:
#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)
Traceback (most recent call last): File "C:\Users\Python\Using_sum.py", line 4, in
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.