Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use sum () in Python

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use sum () in Python, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand.

Foreword:

We can now add multiple values using Python's built-in function sum (). This function provides an efficient, readable, and Pythonic way to solve summation problems in your code. If you are dealing with mathematical calculations that require the summation of values, then it sum () can be your savior.

Python's built-in function sum () is an efficient and Pythonic method for summing numeric lists. Adding multiple numbers is a common intermediate step in many calculations, so sum () is a very convenient tool for Python programmers.

As an additional and interesting use case, you can join lists and tuples using sum (), which is convenient when you need to piece together lists.

In this tutorial, we will learn how to:

Manual summation of values using general techniques and tools

Use Pythonsum () to add multiple values efficiently

Splicing lists and tuples with sum ()

Use sum () to approach the general summation problem

Sum () in the parameter with the appropriate value

Make a choice between sum () and alternative tools to summarize and concatenate objects

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

1. Understanding the problem of summation

Adding 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 will do the following:

1 + 2 + 3 + 4 + 5 = 15

In terms of mathematics, this expression is very simple. It guides 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 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 number list is a long list or a short list.

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

> numbers = [1,2,3,4,5] > total = 0 > > for number in numbers:... Total + = number... > > total15

Here, you first create a total and initialize it to 0. 0. This variable is used as an accumulator where you can store intermediate results until the final result is obtained. The loop iterates over numbers and updates by accumulating each continuous value using augmented assignments. Total

You can also wrap the for loop in a function. In this way, we 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

In sum_numbers (), you take an iterable object-- especially a numeric list-- as a parameter and return the sum of the values in the input list. If the input list is empty, the function returns 0. This for loop is the same as what you saw earlier.

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, the recursive function calls itself in the loop:

> def sum_numbers (numbers):... If len (numbers) = = 0Ru... Return 0... Return numbers [0] + sum_numbers (numbers [1:])... > sum_numbers ([1,2,3,4,5]) 15

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

In the above example, the basic case means that the sum of the zero-length list is 0. The recursive case means that the sum is the first value numbers [0], plus the sum of the rest of the numbers [1:]. Because recursive situations use shorter sequences in each iteration, you want to encounter a basic situation when numbers is a zero-length list. As a final result, you will get the sum numbers of all the items in the input list.

Note: in this example, if you don't check the empty input list (your basic case), sum_numbers () will never encounter an infinite recursive loop. When the length of your numbers list reaches 0, the code attempts to access the items in the empty list, which raises an IndexError and breaks the loop.

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

Another option for summing a list of numbers in Python is to use reduce () from functools. To get the sum of the list of numbers, we can pass any 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

You can call reduce () with reduce or fold, function with iterable together as a parameter. Reduce () then uses the input function to process the iterable and returns a single cumulative value.

In the first example, the reduction function is add (), which adds two numbers. The end result is the sum of the numbers in the input iterable. As a disadvantage, reduce () proposes a TypeError when you iterable it with an empty call.

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

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

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

2. Getting started with Python sum ()

Readability is one of the most important principles behind Python philosophy. When summing a list of values, you can visualize what you want the loop to do. You want it to traverse some numbers, add them to an intermediate variable, and then return the final sum. However, you may be able to imagine a more readable summation version that does not require a loop. You want Python to take some numbers and add them up.

Now think about how to reduce () to sum. Using reduce () is arguably less readable and less straightforward than a loop-based solution.

This is why Python 2.3 is added to 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 values lists:

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

Wow! It's neat, isn't it? It reads like simple English and clearly conveys what you do on the input list. Using sum () is more readable than a for loop or reduce () call. Unlike reduce (), sum () does not throw a TypeError when you provide an empty iterable object. Instead, it understandably returns 0. 0.

We can call sum () with the following two parameters:

Iterable is a required parameter and any Python iterable object can be saved. Iterable objects usually contain numeric values, but they can also contain lists or tuples.

Start is an optional parameter that can save an initial value. Then add the value to the final result. It defaults to 0.

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

In the next two sections, you will learn the basics of the use of sum () in your code.

2.1required parameter: iterable

Accepting any Python iterable as its first parameter makes sum () generic, reusable, and polymorphic. Because of this feature, you can use sum () lists, tuples, collections, 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)

In all of these examples, sum () calculates the arithmetic sum of all 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 defaults to summing keys, and the second example sums keys because .keys () calls 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 sum () to use list deduction as a 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

Python 2.4 added generator expressions to the language. Similarly, sum () works as expected when you use a generator expression as a parameter:

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

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

2.2 optional parameter: start

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

> sum ([1,2,3,4,5], 100) # Positional argument115 > > sum ([1,2,3,4,5], start=100) # Keyword argument115

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

"if you do not provide a value of start for, the default is 0." The default value of 0 ensures that the expected behavior of the sum of the input values is returned.

3. Summation of numerical values

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

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

> 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]) (8room8j) > > # Sum Decimal numbers > sum ([Decimal ("10.2"), Decimal ("12.5")) Decimal]) Decimal ('34.5') > # Sum Fraction numbers > sum ([Fraction (51,5), Fraction (25,2), Fraction (59,5)]) Fraction (69,2)

Here, you use sum () and floating-point numbers for the first time. It is worth noting that the behavior of the function float ("nan") when you use the special symbol inf and nan when calling float ("inf") and middle. The first symbol represents an infinite value, so sum () returns inf. The second symbol represents the NaN (not a number) value. Because you cannot add numbers to non-numbers, you will get nan results.

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

4. Connection sequence

Although sum () is mainly 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)

In these examples, you use sum () to connect lists and tuples. This is an interesting feature that you can use to flatten lists or tuples. The key requirement of these sample work is to select the appropriate value start for. 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 applies only to sequence types that support concatenation, except for strings:

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

When you try to concatenate a string using sum (), you get a TypeError. As the exception message implies, you should use str.join () to concatenate strings in Python. Later, when you move on to the section using the alternative sum () method, you will see an example of using this method.

5. Use Python to practice sum ()

So far, you have learned to use sum (). You have learned how to use this function to add values 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 your code. From these practical examples, you will learn that this built-in function is very convenient when you perform a calculation that needs to find the sum of a series of numbers as an intermediate step.

You'll also learn that this sum () can be helpful when you work with lists and tuples. A special example you'll see is when you need to flatten the list.

5.1 calculate the cumulative sum

The first example you will write is related to how to use the cumulative list summation of logarithmic values for the start parameter.

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 a sales unit report from each point of sale. You need to systematically calculate the cumulative sum to see how many items the entire company has 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_sales119 > tuesday = [12,32,15] > cumulative_sales = sum (tuesday, start=cumulative_sales) > > cumulative_sales178 > wednesday = [20,24,42] > cumulative_sales = sum (wednesday, start=cumulative_sales) > cumulative_sales264.

By using start, you can set an initial value to initialize the sum, which allows you to add contiguous units to the previously calculated subtotal. This weekend, you will get the total number of sales units of the company.

5.2 calculate the average of the sample

Another practical use case of sum () is to use it as an intermediate calculation before further calculation. For example, suppose you need to calculate the arithmetic mean of a numerical sample. The arithmetic mean, also known as the average, 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 up by using Python, you can divide it into two parts. The first part of this calculation, where you add the numbers, is the task sum (). The next part of the operation, divided by 8, uses the number count 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

Here, call sum () 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 desired division to calculate the arithmetic mean of the sample.

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

> # Python > = 3.8 > def average (data_points):... If (num_points: = len (data_points)) = = 0 len... 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 ", line 1, in File", line 3, in averageValueError: average requires at least one data point

In the internal average (), you first check whether the input sample has any data points. If not, then your ValueError triggers with a descriptive message. In this example, you use the walrus operator to store the number of data points in a variable, num_points so that you don't need to call len () again. The return statement calculates the arithmetic mean of the sample and sends it back to the calling code.

Note: averaging data samples is a common operation in statistics and data analysis. The Python standard library provides a convenient module called statistics to handle these types of calculations.

In the statistics module, you will 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 point

The behavior of the statistics.mean () function is very similar to that of average () the function you coded earlier. When you call mean () with a numeric sample, you get the arithmetic mean of the input data. When you pass an empty list to mean (), you get a statistics.StatisticsError.

Note that when you average () with the appropriate sample call, you will get the required average. If you call average () with an empty sample, you will get the results expected by ValueError.

5.3 find the dot product of two sequences

Another problem you can use sum () is to find the dot product of two equal-length sequences of 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), you can manually calculate their dot product using addition and multiplication:

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

To extract consecutive value pairs from the 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

Using zip (), you can generate a list of tuples using the values from each input sequence. The generator expression loops through each tuple, multiplying the previously arranged consecutive value pairs by zip (). The final step is to add products together using 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? In this case, zip () ignores the extra value in the longest sequence, which leads to incorrect results.

To deal with this possibility, we can wrap the call sum () in a 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) Traceback (most recent call last): File ", line 1, in File", line 3, in dot_productValueError: Vectors must have equal sizes

Here, dot_product () takes the two sequences as parameters and returns their corresponding dot product. If the length of the input sequence is different, the function throws a ValueError.

Embedding functionality in custom functions allows you to reuse code. It also gives you the opportunity to name the function descriptively so that the user knows what the function does just by reading the function name.

5.4 flattened list list

Flattening lists is a common task in Python. Suppose you have a list that needs to be flattened to a list that contains all the items in the original nested list. You can use any of several methods to flatten the list 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]

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

But hang on! You have sum () learned in this tutorial how to use to concatenate sequences. Can you use this feature to flatten the list as in the example above? Right! That's what it is:

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

That's fast! 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 final list returned is only the most recently created list of all the lists created in each round of connections. Using list deduction 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]

This new version of flatten_list () is more efficient and less wasteful in terms of memory usage. However, nested understanding can be difficult to read and understand.

Using .append () is probably the easiest way to flatten the list and Pythonic it:

> 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]

In this version of flatten_list (), a person reading your code can see that the function traverses every sublist in a_list. In the first for loop, it iterates through each iteminsublist so that the final flat uses .append (). As with the previous derivation, this solution creates only one list in the process. One advantage of this solution is that it is highly readable.

6. Use the substitute sum ()

As you already know, sum () is generally very helpful for dealing with numeric values. However, Python provides an alternative tool when dealing with floating-point numbers. In math, you will find a function called fsum (), which can help you improve the overall accuracy of floating-point calculations.

You may have a task where you want to connect or link multiple iterable objects so that you can deal with them as a whole. In this case, you can look at the function chain () of the itertools module.

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

6.1Sum of floating point numbers: math.fsum ()

If your code constantly uses the sum of floating-point numbers sum (), you should consider using math.fsum () instead. This function improves the accuracy of the calculation by performing the floating-point calculation sum () more carefully.

According to its documentation, fsum () "avoids loss of precision by tracking the sum of multiple intermediate parts." This document provides the following examples:

> from math import fsum > sum ([.1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.99999999999999 > fsum ([.1, .1, .1, .1, .1, .1]) 1.0

With fsum (), you can get more accurate results. However, you should note that this fsum () does not solve representation errors in floating-point operations. The following example reveals this limitation:

> from math import fsum > sum ([0.1,0.2]) 0.300000000000004 > fsum ([0.1,0.2]) 0.300000000000004

In these examples, the two 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.1virtual .28f}" '0.1000000000000000055511151231' > > f "{0.2virtual .28f}"' 0.20000000000000111022302463'

However, unlike sum (), fsum () can help 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] * 100000.0 > fsum ([1,1, 1e100,-1e100] * 10000) 20000.0

Wow! The second example is very surprising and completely failed sum (). Using sum (), you will get 0. 0 results. This is a far cry from the correct result 20000.0, as you get fsum ().

6.2 join iterable object itertools.chain ()

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

When you call chain (), you get the iterator for the project from the input iterable object. In this case, you can use numbers to access successive projects next (). 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 the list 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]

To use the flattened list chain (), you need to use the iterated unpacking operator (*). This operator unwraps all input iterable objects so that chain () can use them and generate corresponding iterators. The final step is to call list () to build the desired flat list.

6.3 connection string str.join ()

As you have seen, sum () does not concatenate or concatenate strings. If you need to do this, the preferred and fastest tool available in Python 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'

Using .join () is the most efficient way to concatenate strings with Pythonic. Here, you use a list of strings as parameters and build a single string from the input. Note that. Join () uses the string you called the method as the delimiter during the connection. 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.

Thank you for reading this article carefully. I hope the article "how to use sum () in Python" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report