23
loading...
This website collects cookies to deliver better user experience
sum()
of a list. We look at the various methods to do this along with their limitations. sum()
to return the sum of a list that contains the weekly income of employees to calculate monthly income.sum()
function returns the sum of an iterable. Sum()
takes a list (iterable) and returns the sum of the numbers within the list. sum(iterable, start)
Iterable
- Required, iterable can be a list, tuples, and dictionaryStart
- Optional, if passed it the value will be added returned sum#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.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)
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'
TypeError
. Other than this limitation, you can make use of the sum()
function in Python with ease for all summing operations.