📅  最后修改于: 2023-12-03 15:19:01.539000             🧑  作者: Mango
Python's sum
function is a built-in function that returns the sum of all elements in an iterable. The iterable can be any object that can be looped over, including lists, tuples, sets, and even strings.
Here's the basic syntax of the sum
function:
sum(iterable, start=0)
The iterable
parameter is the object that contains the items that you want to sum. The start
parameter is an optional value that represents the starting value of the sum.
For example, let's say we have a list of numbers:
numbers = [1, 2, 3, 4, 5]
We can use the sum
function to find the total sum of the numbers in the list:
total_sum = sum(numbers)
print(total_sum) # Output: 15
We can also provide a starting value for the sum:
total_sum = sum(numbers, 10)
print(total_sum) # Output: 25
In this case, the start
parameter is set to 10
, so the sum
function adds the numbers in the list starting with 10
instead of 0
.
We can use the sum
function with other iterables as well. For example, we can find the sum of all characters in a string:
text = "Hello, World!"
char_sum = sum(ord(c) for c in text)
print(char_sum) # Output: 991
In this example, we first use a generator expression to convert each character in the string into its ASCII code using the ord
function. We then pass this generator expression to the sum
function, which calculates the sum of all ASCII codes.
In conclusion, the sum
function is a powerful tool in Python that allows you to quickly calculate the sum of items in any iterable. Whether you're working with lists, tuples, sets, or strings, the sum
function can help you easily find the total sum of all elements.