Cheap VPS host selection
Provide server host evaluation information

How to use the sum function in python

In Python, sum() Functions can be used to sum values in lists, tuples, or other iterable objects. The following is the use of sum() Basic syntax of function:

 sum (iterable, start)

Among them, iterable Is an iterative object that requires and, start (Optional) is the initial value of the specified sum, which is 0 by default.

For example, if you want to sum a list containing integers, you can use the following code:

 my_list = [ one , two , three , four , five ] result = sum (my_list) print (result) #Output 15 (i.e. 1+2+3+4+5)

If you want to sum integers in the list from 10, you can set start The parameter is set to 10, as shown below:

 my_list = [ one , two , three , four , five ] result = sum (my_list, ten ) print (result) #Output 25 (i.e. 10+1+2+3+4+5)

sum() The function can also be used to sum the numeric values in tuples, collections, or other iterable objects. The usage is similar to the above example.

Note that if there are elements of non numeric type in the iterable object sum() The function will throw a TypeError exception. Therefore, when using sum() Before the function, make sure that all elements are of numeric type.

Do not reprint without permission: Cheap VPS evaluation » How to use the sum function in python