Abstract: Python’s built-in function sum() is an efficient Pythonic way to sum a list of values. Adding up multiple numbers is a common intermediate step in many calculations, so sum() is a very handy tool for Python programmers.

This article is from “Python sum() : Pythonic summation method” by Yuchuan.

Python’s built-in function sum() is an efficient, Pythonic way to sum a list of values. Adding up multiple numbers is a common intermediate step in many calculations, so sum() is a very handy tool for Python programmers.

As an additional and interesting use case, you can join lists and tuples using sum(), which can be handy when you need to collate lists of lists.

In this tutorial, you will learn how to:

  • Sum values manually using common techniques and tools

  • Use **Pythonsum()** to efficiently add multiple values

  • Concatenated lists and tuples with sum()

  • Use sum() to approach the ordinary summation problem

  • Sum () in arguments with appropriate values

  • Choose between sum() and alternative tools to summarize and concatenate objects

This knowledge will help you effectively handle and solve summation problems in your code using sum() or other alternative and specialized tools.

Understanding the summation problem

Adding numeric values is a fairly 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. Using standard arithmetic, you do the following:

1 + 2 + 3 + 4 + 5 = 15

Mathematically, this expression is very simple. It guides you through a series of short additions until you find the sum of all the numbers.

You can do this particular calculation manually, but imagine some other unlikely scenarios. If you have a particularly long list of numbers, adding them manually can be inefficient and error-prone. What happens if you don’t even know how many items are in the list? Finally, imagine a scenario where the number of items you need to add changes dynamically or unpredictably.

In this case, Python is very useful in solving summation problems, whether your list of numbers is a long list or a short list.

If you want to sum numbers by creating your own solution from scratch, you could try using a for loop:

>>>

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

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

>>> total
15
Copy the code

Here, you first create total and initialize it to 0. This variable is used as an accumulator where you can store intermediate results until you get to the final result. The loop iterates through numbers and updates by adding up each successive value using augmented assignment. total

You can also wrap a for loop in a function. This way, you can reuse code for different lists:

>>>

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

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

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

In sum_numbers(), you take an iterable — specifically a list of values — as an argument and return the sum of the values in the input list. If the input list is empty, the function returns 0. The for loop is the same as what you saw before.

You can also use recursion instead of iteration. Recursion is a functional programming technique in which a function is called in its own definition. In other words, a recursive function calls itself in a loop:

>>>

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

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

When you define a recursive function, you run the risk of falling into an infinite loop. To prevent this, you need to define both the base case for stopping recursion and the recursion case for calling a function and starting an implicit loop.

In the example above, the base case means that the sum of zero-length lists is 0. The recursive case means that the sum is the first value numbers[0], plus the sum of the remaining values numbers[1:]. Because the recursive case uses shorter sequences in each iteration, you expect the base case when numbers is a zero-length list. As a final result, you get the sum of all the items in the input list, numbers.

** Note: ** In this example, sum_numbers() never encounters an infinite recursive loop if you don’t check the empty input list (your base case). When your numbers list reaches 0 in length, the code attempts to access items in the empty list, raising IndexError and breaking the loop.

With this implementation, you will never get a sum from this function. You get one every time you IndexError.

Another option for summation over numeric lists in Python is to use reduce()from functools. To get the sum of the list of numbers, you can pass either operator.add or the appropriate lambda function to reduce() as the first argument:

>>>

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

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

>>> reduce(add, [])
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 the code

You can call reduce() with reduce or fold, function with iterable as arguments. Reduce () then processes iterable using input functions and returns a single cumulative value. In the first example, the reduction function is add(), which adds two numbers. The final result is the sum iterable of the numbers in the input. As a drawback, reduce() raises a TypeError when you call it iterable with an empty.

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

Because summations like this are common in programming, writing a new function every time you need to sum over some numbers is a lot of repetitive work. Also, usingReduce () is not the most readable solution you can use.

Python provides specialized built-in functions to solve this problem. This function is conveniently called sum(). Because it is a built-in function, you can use it directly in your code without importing anything.

Introduction to Python sum ()

Readability is one of the most important principles behind the Python philosophy. Visualize what you want to loop through as you sum over a list of values. You want it to iterate over some numbers, add them to an intermediate variable, and then return the final sum. However, you can probably imagine a more readable version of the sum that doesn’t require a loop. You want Python to take some numbers and add them up.

Now think about the sum of reduce(). Using Reduce () is arguably less readable and direct than a lop-based solution.

This is why Python2.3 added sum() as a built-in function to provide a Pythonic solution to the summation problem. Alex Martelli contributed this function, which is now the preferred syntax for summing lists of values:

>>>

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

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

A: wow! It’s neat, isn’t it? It reads like plain English and clearly conveys what you are doing on the input list. Using sum() is more readable than a for loop or reduce() call. As with reduce(), sum() does not raise a TypeError when you supply an empty iterable. Instead, it understandably returns 0.

You can call sum() with the following two arguments:

1. Iterable is a required argument that can hold any Python iterable. Iterable objects usually contain numeric values, but can also contain lists or tuples.

2. Start is an optional parameter that can save an initial value. The value is then added to the final result. It defaults to 0.

Internally, sum() adds the startPlus value iterable from left to right. The values in the input iterable are usually numbers, but you can also use lists and tuples. The optional start argument can accept numbers, lists, or tuples, depending on the content passed to iterable. It can’t take a string.

In the following two sections, you’ll learn the basics of how sum() is used in code.

Required argument: iterable

Taking any Python iterable as its first argument makes sum() generic, reusable, and polymorphic. Thanks to this feature, you can use sum() lists, tuples, sets, 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 the code

In all of these examples, sum() computes the arithmetic sum of all the values in the input iteration, regardless of their type. In both dictionary examples, sum() is called to return the sum of the input dictionary keys. The first example sums keys by default, and the second example sums keys due to.keys() calling the input dictionary.

If your dictionary stores numbers in its values and you want to sum those values instead of keys, you can use.values() as in the.keys() example.

You can also use sum() as a list derivation. Here 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 the code

Python 2.4 adds generator expressions to the language. Similarly, sum() works as expected when you use generator expressions as arguments:

>>>

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

This example demonstrates one of the most Pythonic techniques for solving summation problems. It provides an elegant, readable, and efficient solution in one line of code.

Optional parameter: start

The second optional argument, start, allows you to provide a value to initialize the summation process. This parameter is handy when you need to process cumulative values in order:

>>>

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

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

Here, you provide the initial value 100to start. The net effect is that sum() adds this value to the cumulative sum of the values in the input iterable. Note that you can provide start as a positional or keyword argument. The latter option is more explicit and readable.

If you do not provide the value start, the default is 0. A default value of 0 ensures that the expected behavior of the sum of input values is returned.

Sum over values

The main purpose of sum() is to provide a Pythonic way to add values. So far, you’ve seen how to use this function to sum integers. In addition, sum() can be used with any other numeric Python type, such as float, complex, decimal.Decimal, and fractions.Fraction.

Here are a few examples of values using different numeric types of sum() :

>>>

>>> From decimal import decimal >>> from fractions Import Fraction >>> # Sum floating-point numbers >>> Sum ([10.2, 12.5, 11.8]) 34.5 > > > the sum ([10.2, 12.5, 11.8, float (" inf ")]) inf > > > the sum ([10.2, 12.5, 11.8, float("nan")]) nan >>> # Sum complex numbers >>> sum([3 + 2j, 5 + 6 j]) (8 + 8 j) > > > # Sum Decimal Numbers > > > the Sum ([a Decimal (" 10.2 "), a Decimal (" 12.5 "), Decimal("11.8")]) Decimal('34.5') >>> # Sum Fraction numbers >>> Sum ([Fraction(51, 5), Fraction(25, 2), Fraction(59, 10)) 5)]) Fraction(69, 2)Copy the code

Here, for the first time, you use sum() with floating point numbers. It is worth noting how the function behaves when you use the special symbol INF and nan calls float(” INF “) and float(“nan”). The first symbol represents an infinite value, so sum() returns INF. The second symbol represents a NaN (not a number) value. Because you can’t add numbers to non-numbers, you get nan results.

Other examples sum iterables of complex, Decimal, and Fraction numbers. In all cases, sum() returns the cumulative sum of the results using the appropriate number type.

The connection sequence

Although sum() is primarily used to manipulate numeric values, you can also use this function to concatenate sequences such as lists and tuples. To do this, you need to provide the appropriate value start for:

>>>

>>> 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 the code

In these examples, you use sum() to join lists and tuples. This is an interesting feature that you can use to flatten lists or tuples. The key requirement for these sample jobs is to select the appropriate value start. For example, if you want to join a list, start needs to hold a list.

In the above example, sum() performs concatenation internally, so it only works with sequence types that support concatenation, 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 the code

When you try to concatenate strings with sum(), you get a TypeError. As the exception message implies, you should use str.join() to concatenate strings in Python. You’ll see an example of using this method later when you go into the section using the alternative sum() method.

Sum ()

So far, you’ve learned to use sum(). You’ve learned how to add values using this function, and how to join sequences such as lists and tuples.

In this section, you’ll look at more examples of when and how sum() is used in code. Through these real-world examples, you’ll see how handy this built-in function is when you perform calculations that require finding the sum of a series of numbers as an intermediate step.

You’ll also learn that this sum() is useful when you work with lists and tuples. A special example you’ll see is when you need to flatten a list of lists.

Computational cumulative sum

The first example you’ll write has to do with summing up a cumulative list of values using the start parameter.

Suppose you are developing a system to manage the sale 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 entire 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 the code

By using start, you can set an initial value to initialize the sum, which allows you to add successive units to a previously calculated subtotal. By the end of this week, you will have the total number of units sold by your company.

Calculate the average of the sample

Another practical use case for sum() is to use it as an intermediate calculation before proceeding further. For example, suppose you need to calculate the arithmetic mean of a numerical sample. The arithmetic mean, also known as the mean, is the sum of the values in the sample divided by the number of values or data points.

If you have samples [2, 3, 4, 2, 3, 6, 4, 2] and you want to calculate the arithmetic mean by hand, then you can solve this operation:

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

If you want to speed things up by using Python, you can split it into two parts. The first part of this calculation, where you add up the numbers, is the task of sum(). The next part of the operation, dividing by 8, uses the numbers in the sample. To calculate your divisor, you can use len() :

>>>

>>> points = [2, 3, 4, 2, 3, 6, 4, 2] >>> sum(data_points)/len(data_points) 3.25Copy the code

Here, sum() is called to calculate the sum of the data points in the sample. Next, you use Len () to get the number of data points. Finally, you perform the required division to calculate the arithmetic mean of the sample.

In practice, you might want to convert this code to a function with some additional functionality, such as descriptive names and checking for empty samples:

>>>

> > > > = 3.8 # Python > > > def business (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 ([]) Traceback (most recent call last) File "<stdin>", line 1, in <module> File "<stdin>", line 3, in average ValueError: average requires at least one data pointCopy the code

In internal Average (), you first check to see if there are any data points in the input sample. If not, then you raise ValueError with a descriptive message. In this example, you use the Walrus operator to store the number of data points in variables, num_points so that you don’t need len() to call again. The return statement calculates the arithmetic mean of the sample and sends it back to the calling code.

** Note: ** Calculating the average value of a data sample is a common operation in statistics and data analysis. The Python standard library provides a handy module called Statistics that handles these types of calculations.

In the statistics module, you’ll find a function called 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 pointCopy the code

The statistics.mean() function behaves very similar to the function average() you coded earlier. When you call mean() with a numerical sample, you get the arithmetic average of the input data. When you pass an empty list to mean (), you will get a statistics. StatisticsError. Note that when you average() calls with the appropriate sample, you get the required average. If you average() calls with an empty sample, you get what ValueError expects.

Take the dot product of two sequences

Another problem you can use with sum() is to find the dot product of two sequences of equal length numeric values. The product of the algebraic sum of the dot product is in each pair of values in the input sequence. For example, if you have sequences (1, 2, 3) and (4, 5, 6), then you can manually compute their dot product using addition and multiplication:

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

To extract successive pairs of values from an input sequence, you can use zip(). You can then multiply each pair of values using a generator expression. Finally, sum() can summarize the product:

>>>

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

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

With zip(), you can generate a list of tuples with the values from each input sequence. The generator expression loops through each tuple while multiplying the previously arranged consecutive value pairs by zip(). The final step is to use sum() to add the products together.

The code in the example above works. However, the dot product is defined for sequences of equal length, so what happens if you supply sequences of different lengths? In this case, zip() ignores the extra value in the longest sequence, which results in incorrect results.

To handle this possibility, you can wrap the call sum() in a custom function and provide appropriate checks 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 sizesCopy the code

Here, dot_product() takes two sequences as arguments and returns 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 name functions descriptively so that users know what a function does simply by reading its name.

Flattening list list

Flattening lists lists are a common task in Python. Suppose you have a list of lists that you need to flatten into a list containing all the items in the original nested list. You can use any of several methods to flatten lists in Python. For example, you can use a 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 the code

In a flatten_list(), the flattener loops through all the nested list a_list contained in the flattener. It then connects them flat using the enhanced assignment operation (+=). As a result, you get a flat list containing all the items in the original nested list.

But hang in there! You’ve learned how to use sum() to join sequences in this tutorial. Can you use this feature to flatten the list list as in the example above? Yes! Here it is:

>>>

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

That soon! One line of code, matrix is now a flat list. However, using sum() does not seem to be the fastest solution.

An important drawback of any solution that implies concatenation is that, behind the scenes, each intermediate step creates a new list. This can be very wasteful in terms of memory usage. The list eventually returned is only the most recently created list of all the lists created in each round of connections. Using list comprehensions 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 the code

The new version flatten_list() was more efficient in memory usage and wasted less. However, nested understandings can be difficult to read and understand.

Using.append() is probably the most readable and Pythonic way to flatten lists:

>>>

>>> 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 the code

In this version a flatten_list() a person reading your code could see that the function iterates through every sublist on the a_list. In the first

In the for loop, it iterates through each iteminsublist to use the final flat.append(). As in the previous derivation, this solution creates only a list in the process. One advantage of this solution is that it is very readable.

Use the substitute sum()

As you’ve already seen, sum() is generally helpful for working with numbers. However, Python provides an alternative tool when dealing with floating point numbers. In Math, you’ll find a function called fsum() that can help you improve the overall accuracy of floating-point calculations.

You might have a task where you want to join or link multiple iterables so that you can work with them as a whole. In this case, you can look at function chain() of the iterTools module.

You might also have a task to concatenate a list of strings. As you learned in this tutorial, sum() cannot be used for concatenation strings. This function is not built for string concatenation. The most Pythonic alternative is to use str.join().

Summing floating point numbers: math.fsum()

If your code constantly uses summing sum() over floating point numbers, you should consider math.fsum() instead. This function performs the floating-point calculation sum() more carefully, thus improving the accuracy of the calculation. According to its documentation, fsum() “avoids loss of accuracy by tracking multiple intermediate sums.” The document provides the following examples:

>>>

> > > the from math import fsum > > > the sum ([. 1. 1. 1. 1. 1,. 1, the 1,. 1, the 1,. 1]) 0.9999999999999999 > > > fsum ([. 1. 1. 1. .1,.1,.1,.1,.1,.1]) 1.0Copy the code

Using fsum(), you can get more accurate results. However, you should note that this fsum() does not solve presentation errors in floating-point arithmetic. The following example illustrates this limitation:

>>>

>>> FROM Math import Fsum >>> sum([0.1, 0.2]) 0.30000000000000004 >>> Fsum ([0.1, 0.2]) 0.30000000000000004Copy the code

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

>>>

> > > f "28 f} {0.1:" '0.1000000000000000055511151231' > > > f "28 f} {0.2:" '0.2000000000000000111022302463'Copy the code

Sum (), however, differs from fsum(), which helps you reduce floating point error propagation when you add very large and very small numbers:

>>>

>>> 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.0Copy the code

A: wow! The second example is quite surprising and completely fails sum(). Using sum(), you get 0.0. This is far from the correct result of 20000.0, as you get with fsum().

Join iterables itertools.chain()

If you are looking for a convenient tool to join or link a series of iterables, consider using chain()from itertools. This function can take multiple iterators and build an iterator that produces items from the first, 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 the code

When you call chain(), you get the iterator of the item from the input iterable. In this case, you can access the contiguous item next() in numbers. If you want to use a list, you can use it list() to use the iterator and return a regular Python list.

Chain () is also a good choice to flatten lists in Python:

>>>

>>> 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 the code

To use the flattened list list chain(), you need to use the iterable unpack operator (*). This operator unpacks all input iterables so that chain() can use them and generate the corresponding iterators. The final step is to call list() to build the required flat list.

Join string str.join()

As you’ve already seen, sum() does not concatenate or concatenate strings. If you need to do so, the preferred and fastest tool available in Python is str.join(). This method takes a series of strings as arguments and returns a new connection string:

>>>

>>> greeting = ["Hello,", "welcome to", "Real Python!"]  >>> " ".join(greeting) 'Hello, welcome to Real Python! 'Copy the code

Join () is the most efficient and Pythonic way to concatenate strings. Here, you take a list of strings as arguments and build a single string from the input. Note that.join() uses the string from which you called the method as the delimiter during the join. In this example, you call.join() a string consisting of a single space character (“”), so the original string fromgreeting is separated by Spaces in the final string.

conclusion

You can now add multiple values using Python’s built-in function sum(). This function provides an efficient, readable, Pythonic way to solve summation problems in code. If you’re dealing with math that requires sums over numeric values, sum() can be your savior.

In this tutorial, you learned how to:

  • Sum values using common techniques and tools

  • Effectively add multiple numeric sums () using Python

  • Use the join sequence sum()

  • Use sum() to approach the ordinary summation problem

  • Sum () in argument over iterable and start using appropriate values

  • Choose between sum() and alternative tools to summarize and concatenate objects

Armed with this knowledge, you can now add multiple values in a Pythonic, readable, and efficient manner.

Click to follow, the first time to learn about Huawei cloud fresh technology ~