In this post, we will see about Python sum() function.
Python sum() function is used to sum elements of iterator from start to the end of iterable.It is generally used with numbers only.You can use it with String too but you can not use start incase of string and it is better to concatenate string using ”.join() method.
start is optional argument here and provides start of index from which you want to calculate sum.
- Sum of the iterable from left to right
- If start is provided, it returns start + sum of iterable from left to right
Let’s see a simple example:
#Sum the list l=[1,2,3,4] print(sum(l)) #Sum the list with start 10 l=[1,2,3,4] print(sum(l,10)) #Sum the list of float fList=[1.2,2.3,3.2,4.9] print(sum(fList)) #Sum the list of float with start 2.6 fList=[1.2,2.3,3.2,4.9] print(sum(fList,2.6))
It is recommended to use math.fsum() in case of floating points.
That’s all about python sum function.