# Python sum (): the summation method of Python

2022-01-29 17:16:09

​​ Abstract ：Python Built in functions for sum() It is an effective and Pythonic Methods . Adding multiple numbers is a common intermediate step in many calculations , therefore sum() about Python It is a very convenient tool for programmers .

This article is shared from Huawei cloud community 《Python Of sum()：Pythonic Summation method of 》, author ： Yuchuan .

Python Built in functions for sum() It is an effective and Pythonic Methods . Adding multiple numbers is a common intermediate step in many calculations , therefore sum() about Python It is a very convenient tool for programmers .

As an additional and interesting use case , You can connect lists and tuples using sum(), When you need to put together a list of lists , It can be very convenient .

In this tutorial , You will learn how to ：

• Use General technology and tools Sum the values manually

• Use **Pythonsum()** Efficiently add multiple values

• Splice lists and tuples And sum()

• Use sum() Close to ordinary Summation problem

• Use appropriate values for Parameters in sum()

• Make a choice between sum() and Alternative tools To summarize and concatenate objects

This knowledge will help you use sum() Or other alternative and special tools to effectively deal with and solve the summation problem in the code .

## Understanding summation problems

Adding values is a very common problem in programming . for example , Suppose you have a list of numbers [1, 2, 3, 4, 5] And want to add them together to calculate their sum . Use standard arithmetic , You will do the following ：

1 + 2 + 3 + 4 + 5 = 15

As far as mathematics is concerned , This expression is very simple . It will guide you through a series of short additions , Until you find the sum of all the numbers .

This particular calculation can be done manually , But imagine other unlikely situations . If you have a particularly long list of numbers , Adding manually can be inefficient and error prone . What happens if you don't even know how many items in the list ？ Last , Imagine a scene , The number of items you need to add changes dynamically or unpredictably .

under these circumstances , Whether your list of numbers is long or short ,Python Solving Summation problem They are very useful .

If you want to sum numbers by creating your own solution from scratch , Then you can try using for loop ：

>>>

``````>>> numbers = [1, 2, 3, 4, 5]
>>> total = 0

>>> for number in numbers:
...     total += number
...

>>> total
15
Copy code ``````

ad locum , You first create total And initialize it to 0. This variable is used as an accumulator , You can store intermediate results in it , Until we get the final result . The loop iterates by accumulating each successive value using an augmented assignment numbers And update .total

You can also for Loop wrapped in function . such , You can reuse code for different lists ：

>>>

``````>>> def sum_numbers(numbers):
...     total = 0
...     for number in numbers:
...         total += number
...

>>> sum_numbers([1, 2, 3, 4, 5])
15

>>> sum_numbers([])
0
Copy code ``````

stay sum_numbers() in , You will an iteratable object —— In particular, a list of values —— As a parameter , And returns the sum of the values in the input list . If the input list is empty , Then the function returns 0. The for The loop is the same as you saw earlier .

You can also use recursion instead of iteration . Recursion is a functional programming technique , Where the function is called in its own definition . let me put it another way , Recursive functions call themselves in loops. ：

>>>

``````>>> def sum_numbers(numbers):
...     if len(numbers) == 0:
...         return 0
...     return numbers + sum_numbers(numbers[1:])
...

>>> sum_numbers([1, 2, 3, 4, 5])
15
Copy code ``````

When you define a recursive function , You risk falling into an infinite cycle . To prevent this , You need to define how to stop recursion Basic information And calling a function and starting an implicit loop Recursive case .

In the example above , The basic case means that the sum of zero length lists is 0. The recursive case means that the sum is the first value numbers, Add the sum of the remaining values numbers[1:]. Because of recursion, a shorter sequence is used in each iteration , So you want to numbers Is the basic case encountered when a zero length list . As a result , You will get the sum of all items in the input list numbers.

** Be careful ：** In this example , If you do not check the empty input list （ Your basic information ）, be sum_numbers() Never encounter an infinite recursive loop . When your numbers List length reached 0 when , The code will try to access items in an empty list , This will trigger IndexError And break the loop .

Using this implementation , You'll never get a sum from this function . you IndexError You get one every time .

stay Python Another option for summing a list of numbers in is to use reduce()from functools. To get the sum of a list of numbers , You can either operator.add Or appropriate lambda Function is passed as the first argument to reduce()：

>>>

``````>>> from functools import reduce
>>> from operator import add

>>> reduce(add, [1, 2, 3, 4, 5])
15

Traceback (most recent call last):
...
TypeError: reduce() of empty sequence with no initial value

>>> reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
15
Copy code ``````

You can call reduce() With reduction or folding ,function With iterable As a parameter . then reduce() Processing with input functions iterable And returns a single cumulative value . In the first example , The reduction function is add(), It adds two numbers . The end result is input Sum of numbers in iterable. As a disadvantage ,reduce() Came up with a TypeError When you call it with an empty iterable.

In the second example , The reduction function is a lambda Function that returns the addition of two numbers .

Because summation like this is common in programming , Therefore, writing a new function every time you need to sum some numbers is a lot of repetitive work . Besides , usingreduce() Not the most readable solution available to you .

Python Special built-in functions are provided to solve this problem . This function is conveniently called sum(). Because it is a built-in function , So you can use it directly in your code , Without having to import anything .

## Python introduction sum()

Readability is Python One of the most important principles behind Philosophy . When summing a list of values , Visualize what you want the loop to do . You want it to traverse some numbers , Add them up to an intermediate variable , Then return to the final sum . however , You might imagine a more readable summation version that doesn't need a loop . You want to Python Take some numbers and add them up .

Now think about it reduce() Sum up . Use reduce() It's arguably less readable than a loop based solution , More indirect .

That's why will Python2.3 add to sum() For built-in functions to provide... For summation problems Pythonic The reason for the solution .Alex Martelli Contributed this function , It is now the preferred syntax for summing lists of values ：

>>>

``````>>> sum([1, 2, 3, 4, 5])
15

>>> sum([])
0
Copy code ``````

wow ！ It's neat , isn't it? ？ It reads like simple English , And clearly communicate what you do on the input list . Use sum() Than for Cycle or reduce() Call more readable . And reduce(), When you provide an empty iteratable object sum() Not trigger a TypeError. contrary , It understandably returns 0.

You can sum() Call with the following two parameters ：

1. iterable Is a required parameter , You can save anything Python Iteratable object . Iteratable objects usually contain numeric values , But it can also contain lists or tuples .

2. start Is an optional parameter , You can save an initial value . Then add the value to the final result . It defaults to 0.

In the internal , From left to right sum() add to startplus The value in iterable. Input iterable Values in are usually numbers , But you can also use lists and tuples . Optional parameters start Acceptable number 、 List or tuple , It depends on passing it on to The content of iterable. It can't take one string.

In the following two sections , You will learn sum() Basics for use in code .

Required parameters ： iterable

Accept anything Python iterable As its first parameter, it makes sum() Generic 、 Reusable and polymorphic . Because of this function , You can use sum() list 、 Tuples 、 aggregate 、range Objects and dictionaries ：

>>>

``````>>> # Use a list
>>> sum([1, 2, 3, 4, 5])
15

>>> # Use a tuple
>>> sum((1, 2, 3, 4, 5))
15

>>> # Use a set
>>> sum({1, 2, 3, 4, 5})
15

>>> # Use a range
>>> sum(range(1, 6))
15

>>> # Use a dictionary
>>> sum({1: "one", 2: "two", 3: "three"})
6
>>> sum({1: "one", 2: "two", 3: "three"}.keys())
6
Copy code ``````

In all of these examples ,sum() Calculates the arithmetic sum of all values in the input iteration , Regardless of their type . In two dictionary examples , All call sum() Returns the sum of the input dictionary keys . The first example sums the keys by default , The second example is due to .keys() Call the input dictionary to sum the keys .

If your dictionary stores numbers in its values , And you want to sum these values instead of keys , Then you can .values() image .keys() Use as in the example .

You can also sum() Use list derivation as parameter . This is an example of calculating the sum of squares of a series of values ：

>>>

``````>>> sum([x ** 2 for x in range(1, 6)])
55
Copy code ``````

Python 2.4 Added a generator expression to the language . Again ,sum() When you use a generator expression as an argument , Work as expected ：

>>>

``````>>> sum(x ** 2 for x in range(1, 6))
55
Copy code ``````

This example shows the best way to solve the sum problem Pythonic One of the technologies . It provides an elegant... In one line of code 、 Readable and efficient solution .

Optional parameters ： start

The second optional parameter start Allows you to provide a value to initialize the summation process . When you need to process cumulative values sequentially , This parameter is very convenient ：

>>>

``````>>> sum([1, 2, 3, 4, 5], 100)  # Positional argument
115

>>> sum([1, 2, 3, 4, 5], start=100)  # Keyword argument
115
Copy code ``````

ad locum , You provide the initial value 100to start. The net effect is sum() Add this value to the cumulative sum of the values in the input iterations . Please note that , You can start Provided as a positional or keyword parameter . The latter option is more explicit and readable .

If you are not for Provide value start, The default is 0. The default value is 0 Ensure the expected behavior of returning the sum of input values .

## Sum values

sum() The main purpose of is to provide a Pythonic Method to add values . up to now , You've seen how to use this function to sum integers . Besides , have access to sum() Any other number Python type , such as float,complex,decimal.Decimal, and fractions.Fraction.

Here are the USES sum() Several examples of values of different numeric types ：

>>>

``````>>> from decimal import Decimal
>>> from fractions import Fraction

>>> # Sum floating-point numbers
>>> sum([10.2, 12.5, 11.8])
34.5
>>> sum([10.2, 12.5, 11.8, float("inf")])
inf
>>> sum([10.2, 12.5, 11.8, float("nan")])
nan

>>> # Sum complex numbers
>>> sum([3 + 2j, 5 + 6j])
(8+8j)

>>> # Sum Decimal numbers
>>> sum([Decimal("10.2"), Decimal("12.5"), Decimal("11.8")])
Decimal('34.5')

>>> # Sum Fraction numbers
>>> sum([Fraction(51, 5), Fraction(25, 2), Fraction(59, 5)])
Fraction(69, 2)
Copy code ``````

ad locum , Your first use sum() And floating-point Numbers . It is worth noting that , When you use special symbols inf and nan Calling float("inf") and float("nan") Behavior of time function in . The first symbol represents a Infinite value , therefore sum() return inf. The second symbol represents NaN（ Not numbers ） value . Because you can't add numbers to non numbers , So you will get nan result .

Sum of other examples iterables Of complex,Decimal and Fraction Numbers . In all cases ,sum() Returns the cumulative sum of the results using the appropriate number type .

## Connection sequence

Even though sum() It is mainly used to operate numerical values , But you can also use this function to connect sequences such as lists and tuples . So , You need to Provide appropriate values start：

>>>

``````>>> num_lists = [[1, 2, 3], [4, 5, 6]]
>>> sum(num_lists, start=[])
[1, 2, 3, 4, 5, 6]

>>> # Equivalent concatenation
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]

>>> num_tuples = ((1, 2, 3), (4, 5, 6))
>>> sum(num_tuples, start=())
(1, 2, 3, 4, 5, 6)

>>> # Equivalent concatenation
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
Copy code ``````

In these examples , You use sum() Connection list and tuple . This is an interesting feature , You can use it to flatten lists or tuples . The key requirement of these sample work is to Select the appropriate value start. for example , If you want to connect to the list , be start Need to hold a list .

In the example above ,sum() Connect internally , Therefore, it only applies to sequence types that support connections , Except strings ：

>>>

``````>>> num_strs = ["123", "456"]
>>> sum(num_strs, "0")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]
Copy code ``````

When you try to use sum() When connecting strings , You'll get a TypeError. As the exception message implies , You should use str.join() To connect Python String in . later , When you enter use substitution sum() Method part , You will see an example of using this method .

## Use Python Practising sum()

up to now , You have learned to use sum(). You have learned how to use this function to add values , And how to connect sequences such as lists and tuples .

In this section , You'll see more about when and how sum() Examples used in code . Through these practical examples , You'll learn that when you perform a calculation that needs to find the sum of a series of numbers as an intermediate step , This built-in function is very convenient .

You will also learn about this sum() It's helpful when you use lists and tuples . A special example you'll see is when you need to flatten the list .

## Calculate the cumulative sum

The first example you will write is related to how to take advantage of start Parameter is related to the summation of the cumulative list of values .

Suppose you are developing a system to manage the sales of a given product at multiple different points of sale . Every day , You will receive sales unit reports from each point of sale . You need to systematically calculate the cumulative sum , To see how many items the whole company sold in a week . To solve this problem , You can use sum()：

>>>

``````>>> cumulative_sales = 0

>>> monday = [50, 27, 42]
>>> cumulative_sales = sum(monday, start=cumulative_sales)
>>> cumulative_sales
119

>>> tuesday = [12, 32, 15]
>>> cumulative_sales = sum(tuesday, start=cumulative_sales)
>>> cumulative_sales
178

>>> wednesday = [20, 24, 42]
>>> cumulative_sales = sum(wednesday, start=cumulative_sales)
>>> cumulative_sales
264
...
Copy code ``````

By using start, You can set an initial value to initialize the sum , This allows you to add continuous units to the subtotal of the previous calculation . This weekend , You will get the total number of sales units of the company .

## Calculate the average of the samples

sum() Another practical use case for is to use it as an intermediate calculation before making further calculations . for example , Suppose you need to calculate the arithmetic mean of a numerical sample . Arithmetic mean , Also known as Average , Is the sum of the values in the sample divided by the number of values or data points .

If you have a sample [2, 3, 4, 2, 3, 6, 4, 2] And you want to calculate the arithmetic mean manually , Then you can solve this operation ：

(2 + 3 + 4 + 2 + 3 + 6 + 4 + 2) / 8 =3.25

If you want to use Python Speed up , You can divide it into two parts . The first part of this calculation , That is, you add the numbers , yes sum() The task of . The next part of the operation , Divided by 8, Count using the numbers in the sample . To calculate your divisor , You can use len()：

>>>

``````>>> data_points = [2, 3, 4, 2, 3, 6, 4, 2]

>>> sum(data_points) / len(data_points)
3.25
Copy code ``````

ad locum , call sum() Calculate the sum of data points in the sample . Next , You use len() To get the number of data points . Last , You perform the required division to calculate the arithmetic mean of the samples .

In practice , You may want to convert this code into a function with some additional functionality , For example, descriptive names and check empty samples ：

>>>

``````>>> # Python >= 3.8

>>> def average(data_points):
...     if (num_points := len(data_points)) == 0:
...         raise ValueError("average requires at least one data point")
...     return sum(data_points) / num_points
...

>>> average([2, 3, 4, 2, 3, 6, 4, 2])
3.25

>>> average([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in average
ValueError: average requires at least one data point
Copy code ``````

In the internal average(), You first check whether the input sample has any data points . without , So you ValueError Trigger with a descriptive message . In this example , You use walrus Operator stores the number of data points in a variable ,num_points So you don't have to len() Call again . The return Statement calculates the arithmetic mean of the sample , And send it to the callback code .

** Be careful ：** Calculating the average of data samples is a common operation in statistics and data analysis .Python The standard library provides a convenient module , be called statistics Handle these types of calculations .

stay statistics Module , You will find one named Function of mean()：

>>>

``````>>> from statistics import mean

>>> mean([2, 3, 4, 2, 3, 6, 4, 2])
3.25

>>> mean([])
Traceback (most recent call last):
...
statistics.StatisticsError: mean requires at least one data point
Copy code ``````

The statistics.mean() The behavior of a function is related to average() The functions you coded earlier are very similar . When you mean() When calling with numeric samples , You will get the arithmetic mean of the input data . When you pass an empty list to mean() when , You will get a statistics.StatisticsError. Please note that , When you average() When called with the appropriate sample , You will get the required average . If you average() Call with empty sample , Then you will get ValueError Expected results .

## Find the dot product of two sequences

Another question you can use sum() Is to find the dot product of two numerical sequences of equal length . The product of the algebraic sum of dot products in each pair of values of the input sequence . for example , If you have a sequence (1, 2, 3) and (4, 5, 6), Then you can use addition and multiplication to manually calculate their dot product ：

1 × 4 + 2 × 5 + 3 × 6 = 32

To extract consecutive value pairs from the input sequence , You can use zip(). You can then use a generator expression to multiply each pair of values . Last ,sum() Can summarize products ：

>>>

``````>>> x_vector = (1, 2, 3)
>>> y_vector = (4, 5, 6)

>>> sum(x * y for x, y in zip(x_vector, y_vector))
32
Copy code ``````

Use zip(), You can generate a tuple list using the values from each input sequence . The generator expression loops through each tuple , At the same time, multiply the previously arranged continuous value pairs by zip(). The last step is to use Add products together sum().

The code in the above example is valid . However , Dot products are defined for sequences of equal length , So what happens if you provide sequences of different lengths ？ under these circumstances ,zip() Ignore extra values in the longest sequence , This can lead to incorrect results .

To deal with this possibility , You can wrap the call sum() In the custom function , And provide an appropriate check for the length of the input sequence ：

>>>

``````>>> def dot_product(x_vector, y_vector):
...     if len(x_vector) != len(y_vector):
...         raise ValueError("Vectors must have equal sizes")
...     return sum(x * y for x, y in zip(x_vector, y_vector))
...

>>> dot_product((1, 2, 3), (4, 5, 6))
32

>>> dot_product((1, 2, 3, 4), (5, 6, 3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in dot_product
ValueError: Vectors must have equal sizes
Copy code ``````

here ,dot_product() Take two sequences as parameters and return their corresponding dot product . If the length of the input sequence is different , The function raises a ValueError.

Embedding functionality in custom functions allows you to reuse code . It also gives you the opportunity to give descriptive names to functions , So that users can know the function of the function only by reading the function name .

## Flatten list

The flatten list is Python A common task in . Suppose you have a list , You need to flatten it into a list that contains all the items in the original nested list . You can use any of several methods in Python Flatten list in . for example , You can use for loop , As shown in the following code ：

>>>

``````>>> def flatten_list(a_list):
...     flat = []
...     for sublist in a_list:
...         flat += sublist
...     return flat
...

>>> matrix = [
...     [1, 2, 3],
...     [4, 5, 6],
...     [7, 8, 9],
... ]

>>> flatten_list(matrix)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy code ``````

stay flatten_list() in , Loop traversal All nested lists contained in a_list. And then it flat Using enhanced assignment operations ( +=) Connect them together . result , You will get a list of planes , It contains all the items in the original nested list .

But hold on ！ You have sum() In this tutorial, you learned how to use to connect sequences . Can you use this feature to flatten the list as in the example above ？ Yes ！ this is it ：

>>>

``````>>> matrix = [
...     [1, 2, 3],
...     [4, 5, 6],
...     [7, 8, 9],
... ]

>>> sum(matrix, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy code ``````

That's fast ！ One line of code ,matrix Now it is a flat list . however , Use sum() It doesn't seem to be the fastest solution .

An important disadvantage of any solution that implies concatenation is , Behind the scenes , Each intermediate step creates a new list . This can be very wasteful in memory usage . The final returned list is only the most recently created list among all the lists created in each round of connection . Using list derivation ensures that you create and return only one list ：

>>>

``````>>> def flatten_list(a_list):
...     return [item for sublist in a_list for item in sublist]
...

>>> matrix = [
...     [1, 2, 3],
...     [4, 5, 6],
...     [7, 8, 9],
... ]

>>> flatten_list(matrix)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy code ``````

This new version flatten_list() More efficient in memory usage , Less waste . However , Nested understanding can be difficult to read and understand .

Use .append() Flat lists are probably the most readable and Pythonic The way ：

>>>

``````>>> def flatten_list(a_list):
...     flat = []
...     for sublist in a_list:
...         for item in sublist:
...             flat.append(item)
...     return flat
...

>>> matrix = [
...     [1, 2, 3],
...     [4, 5, 6],
...     [7, 8, 9],
... ]

>>> flatten_list(matrix)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy code ``````

In this version flatten_list(), A person reading your code can see , Function traverses each sublist stay a_list. At the first

for In circulation , It traverses each iteminsublist In the end flat Use .append(). Just like the previous derivation , The solution creates only one list in the process . One of the advantages of this solution is its readability .

## Use alternatives sum()

As you already know ,sum() Generally speaking , It is very helpful for dealing with numerical values . however , When processing floating point numbers ,Python An alternative tool is provided . stay math in , You will find a function named fsum(), It can help you improve the overall accuracy of floating-point calculations .

You may have a task , You want to connect or link multiple iteratable objects , So that you can treat them as a whole . In this case , You can view itertools Modular function chain().

You may also have a task to connect the string list . What you learned in this tutorial , unable sum() Used to connect strings . This function is not built for string concatenation . most Pythonic An alternative is to use str.join().

## Sum floating point numbers ：math.fsum()

If your code is constantly used Sum floating point numbers sum(), Then you should consider math.fsum() change to the use of sth. . This function ratio Perform floating-point calculations more carefully sum(), So as to improve the calculation accuracy . According to its documentation ,fsum()“ The loss of accuracy is avoided by tracking multiple intermediate parts and .” This document provides the following examples ：

>>>

``````>>> from math import fsum

>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999

>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
Copy code ``````

Use fsum(), You can get more accurate results . however , You should pay attention to this fsum() It does not solve the representation error in floating-point operation . The following example reveals this limitation ：

>>>

``````>>> from math import fsum

>>> sum([0.1, 0.2])
0.30000000000000004

>>> fsum([0.1, 0.2])
0.30000000000000004
Copy code ``````

In these examples , Both functions return the same result . This is because it is impossible to accurately represent these two values 0.1 and 0.2 Binary floating point numbers ：

>>>

``````>>> f"{0.1:.28f}"
'0.1000000000000000055511151231'

>>> f"{0.2:.28f}"
'0.2000000000000000111022302463'
Copy code ``````

sum() however , And The difference is ,fsum() When you add very large and very small numbers , Can help you reduce floating point error propagation ：

>>>

``````>>> from math import fsum

>>> sum([1e-16, 1, 1e16])
1e+16
>>> fsum([1e-16, 1, 1e16])
1.0000000000000002e+16

>>> sum([1, 1, 1e100, -1e100] * 10_000)
0.0
>>> fsum([1, 1, 1e100, -1e100] * 10_000)
20000.0
Copy code ``````

wow ！ The second example is very surprising and completely failed sum(). Use sum(), You will get 0.0 result . This is related to 20000.0 The correct result is far from the correct result , As you can see fsum().

## Connecting iteratable objects itertools.chain()

If you are looking for a convenient tool to connect or link a series of iteratable objects , Please consider using chain()from itertools. This function can take multiple iterators and build an iterator , The iterator starts from the first 、 Project generated in the second , And so on , Until all input iterations are exhausted ：

>>>

``````>>> from itertools import chain

>>> numbers = chain([1, 2, 3], [4, 5, 6], [7, 8, 9])
>>> numbers
<itertools.chain object at 0x7f0d0f160a30>
>>> next(numbers)
1
>>> next(numbers)
2

>>> list(chain([1, 2, 3], [4, 5, 6], [7, 8, 9]))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy code ``````

When you call chain() when , You will get the iterator of the project from the input iteratable object . In this case , You can numbers Use to access sequential items next(). If you want to use a list , Then you can use it list() To use the iterator and return a regular Python list .

chain() stay Python Flattening the list in is also a good choice ：

>>>

``````>>> from itertools import chain

>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> list(chain(*matrix))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy code ``````

To use Flattened list chain(), You need to use Iterative unpacking operator ( *). This operator unpacks all input iteratable objects , In order to chain() You can use them and generate corresponding iterators . The last step is to call list() To build the desired list of planes .

## Connection string str.join()

As you have seen ,sum() Do not connect or connect strings . If you need to do so , that Python The preferred and fastest tool available in is str.join(). This method takes a series of strings as parameters and returns a new connection string ：

>>>

``````>>> greeting = ["Hello,", "welcome to", "Real Python!"]

>>> " ".join(greeting)
'Hello, welcome to Real Python!'
Copy code ``````

Use .join() Is the most valid and of the connection string Pythonic The way . ad locum , You use a list of strings as parameters and build a single string from the input . Please note that ,.join() Use the string of the method you call as the delimiter during the connection . In this example , You call .join() Consists of a single space character ( "") Composed string , So the original string fromgreeting Separated by spaces in the final string .

## Conclusion

You can now use Python Built in functions for sum() Add multiple values . This function provides an efficient 、 Readable and Pythonic To solve the problems in the code Summation problem . If you are dealing with a mathematical calculation that requires summation of values , Then it sum() Can be your Savior .

In this tutorial , You learned how to ：

• Use General technology and tools for Numerical summation

• Use Python Effectively add multiple values sum()

• Use Connection sequence sum()

• Use sum() Close to ordinary Summation problem

• Use appropriate values for iterable and start debate in sum()

• Make a choice between sum() and Alternative tools To summarize and concatenate objects

With this knowledge , You can now Pythonic、 Add multiple values in a readable and efficient manner .

Click to follow , The first time to learn about Huawei's new cloud technology ~