Home > Backend Development > Python Tutorial > Detailed explanation of the summation function sum() in python

Detailed explanation of the summation function sum() in python

醉折花枝作酒筹
Release: 2021-04-27 09:19:23
forward
6747 people have browsed it

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.

Detailed explanation of the summation function sum() in python

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
Copy after login

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
Copy after login

In fact, what we know about the syntax of the sum() function is this

sum(iterable[, start])
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template