Note
Python - sum() - Add all values in an iterable
Overview of the Python sum() function. Sum up provided iterable and return result.
sum(iterable, start=0) simple function that will sum up provided iterable (such as a list or tuple) and return result.
This function is primarily intended for use with numeric data.
sum() accepts optional argument start that will be also added to the sum or returned as a default if iterable is empty.
my_list = [17, 0.5, 99]
my_sum = sum(my_list)
print(my_sum) # 116.5
Output:
116.5
Using sum() with a tuple and an optional start argument
my_tuple = (17, 0.5, 99)
my_sum = sum(my_tuple, start=100)
print(my_sum) # 216.5
Output:
216.5
Using sum() with an empty iterable and an optional startargument as default
my_list = []
my_sum = sum(my_list, start=100)
print(my_sum) # 100
Output:
100
Key Points to Remember about sum()
-
Intended for Numeric Data:
sum()is designed for summing numeric data. Using it on other types will raise aTypeError. -
Optional
startargument: Thestartvalue is useful for setting an initial value or handling empty iterables. -
Efficiency:
sum()is optimized for summing numbers and is generally faster than using a loop for that purpose.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!