Home >Backend Development >Python Tutorial >Detailed explanation of the summation function sum() in python
This article introduces you to the usage of python summation function sum(). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
I originally wanted to calculate the sum of several Int values. I thought it was a simple thing, but the result turned out to be very sad, for example
>>>sum = sum(1,2,3) #结果很明显出现问题报错 TypeError: sum expected at most 2 arguments, got 3
Silly I thought I could only calculate the sum of the first two numbers to be equal to 3, so I tried again
>>>sum = sum(1,2) #结果还是报错 TypeError: 'int' object is not iterable
In fact, what we know about the syntax of the sum() function is this
sum(iterable[, start])
where
iterable – Iterable objects, such as: list, tuple, set, dictionary.
start – Specifies the parameters for addition. If this value is not set, it defaults to 0.
That is to say, the final value obtained by sum() = the sum of the numbers in the iterable object (dictionary: key value addition) start value (if start is not written value, the default is 0) Therefore, the sum of the several int values I want can be written like this
>>>sum = sum([1,2,3]) # in list 6
If we add start, it should be like this
>>> sum = sum([1,2,3],5) #in list +start 11 >>> sum = sum((1,2,3)) #in tuple 6 >>> sum = sum({1,2,3}) #in set 6 >>> sum = sum({1:5,2:6,3:7}) #in dictionary key 6 >>> sum = sum(range(1,4)) #in range() 6
The above is the detailed content of Detailed explanation of the summation function sum() in python. For more information, please follow other related articles on the PHP Chinese website!