Как использовать сумму списка в Python?
Python’s sum(): The Pythonic Way to Sum Values
Python’s built-in function sum()
is an efficient and Pythonic way to sum a list of numeric values. Adding several numbers together is a common intermediate step in many computations, so sum()
is a pretty handy tool for a Python programmer.
As an additional and interesting use case, you can concatenate lists and tuples using sum()
, which can be convenient when you need to flatten a list of lists.
Understanding the Summation Problem
Summing numeric values together is a fairly common problem in programming. For example, say you have a list of numbers [1, 2, 3, 4, 5] and want to add them together to compute their total sum. With standard arithmetic, you’ll do something like this:
1 + 2 + 3 + 4 + 5 = 15
As far as math goes, this expression is pretty straightforward. It walks you through a short series of additions until you find the sum of all the numbers.
It’s possible to do this particular calculation by hand, but imagine some other situations where it might not be so possible. If you have a particularly long list of numbers, adding by hand 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 situations like these, whether you have a long or short list of numbers, Python can be quite useful to solve summation problems.
If you want to sum the numbers by creating your own solution from scratch, then you can try using a for
loop:
Here, you first create total
and initialize it to 0
. Then, you iterate over each number in the list numbers
and add it to total
. Finally, total
will contain the sum of all the numbers in the list.
Getting Started With Python’s sum()
Python’s built-in sum()
function provides a much more concise and efficient way to sum a list of numbers. The syntax for using sum()
is straightforward:
Let’s break down the arguments of the sum()
function:
The Required Argument: iterable
The iterable
argument is the list, tuple, or any other iterable containing the values you want to sum. It can be any iterable object, including lists, tuples, sets, and even strings. Here’s an example using a list:
The sum()
function takes the numbers
list as its iterable
argument and returns the sum of all the numbers in the list.
The Optional Argument: start
The start
argument is an optional argument that specifies the starting value of the sum. If you don’t provide a value for start
, it defaults to 0
. You can use start
to add an initial value to the sum. Here’s an example:
In this example, the start
argument is set to 10
, so the sum will start from 10 instead of 0. The result will be 25
, which is the sum of all numbers in the list plus the initial value of 10
.
Summing Numeric Values
Now that you understand the basics of using sum()
, let’s explore some examples of summing numeric values in more detail.
Example 1: Simple Sum
You can use sum()
to sum a simple list of numeric values. Here’s an example:
The sum()
function takes the numbers
list as its iterable
argument and returns the sum of all the numbers in the list. The output will be 15
, which is the sum of all the numbers in the list.
Example 2: Sum of Floating-Point Numbers
You can also sum floating-point numbers using sum()
. Here’s an example:
The sum()
function works with floating-point numbers just as well as with integers. The output will be 17.6
, which is the sum of all the floating-point numbers in the list.
Example 3: Sum of Multiple Lists
If you have multiple lists that you want to sum together element-wise, you can use sum()
with zip()
. Here’s an example:
In this example, the zip()
function takes the elements from numbers1
and numbers2
and groups them into pairs. Then, the inner sum()
function sums each pair of numbers. Finally, the outer sum()
function sums all the sums together, resulting in a total sum.
Concatenating Sequences
Another interesting use case of the sum()
function is concatenating sequences of strings, lists, or tuples. This can be useful when you need to flatten a list of lists. Here’s an example:
The sum()
function concatenates the lists in lists
by adding them together. By providing an empty list []
as the start
argument, the individual lists are concatenated together into a single flat list. The output will be [1, 2, 3, 4, 5, 6]
, which is the flattened version of the nested list.
Practicing With Python’s sum()
Now that you have an understanding of how to use sum()
, let’s practice with some additional examples to further solidify your knowledge.
Example 1: Computing Cumulative Sums
You can use sum()
to compute the cumulative sum of a list of numbers. Here’s an example:
In this example, a list comprehension is used to iterate over each index in the numbers
list and compute the cumulative sum up to that index. Each value is obtained by using sum()
with a slice of the numbers
list. The output will be [1, 3, 6, 10, 15]
, which is the cumulative sum of the numbers list.
Example 2: Calculating the Mean of a Sample
You can use sum()
to calculate the mean (average) of a list of numbers. Here’s an example:
The sum()
function calculates the sum of all the numbers in the numbers
list. Dividing the sum by the length of the list gives you the mean value. The output will be 3.0
, which is the mean of the numbers list.
Example 3: Finding the Dot Product of Two Sequences
You can use sum()
to find the dot product of two sequences. Here’s an example:
In this example, the zip()
function takes the elements from numbers1
and numbers2
and groups them into pairs. Then, the inner sum()
function calculates the dot product of each pair of numbers by multiplying them together. The output will be 32
, which is the dot product of the two sequences.
Example 4: Flattening a List of Lists
You can use sum()
to flatten a list of lists. Here’s an example:
The sum()
function concatenates the lists in lists
by adding them together. By providing an empty list []
as the start
argument, the individual lists are concatenated together into a single flat list. The output will be [1, 2, 3, 4, 5, 6]
, which is the flattened version of the nested list.
Using Alternatives to sum()
While sum()
is a convenient and efficient tool for summing numerical values, there are some alternatives that you can use depending on your specific needs.
Summing Floating-Point Numbers: math.fsum()
If you need to sum floating-point numbers with higher precision, you can use the math.fsum()
function. Here’s an example:
The math.fsum()
function provides a more accurate sum for floating-point numbers than sum()
. The output will be 0.5
, which is the more accurate sum of the numbers.
Concatenating Iterables With itertools.chain()
If you need to concatenate multiple iterables together, you can use the itertools.chain()
function. Here’s an example:
The itertools.chain()
function takes multiple iterables as arguments and returns an iterator that produces each element from the input iterables as if they were concatenated. The from_iterable()
method is used to efficiently flatten the nested list. The output will be [1, 2, 3, 4, 5, 6]
, which is the flattened version of the nested list.
Concatenating Strings With str.join()
If you need to concatenate strings together, you can use the str.join()
method. Here’s an example:
The join()
method takes an iterable of strings as its argument and returns a single string that concatenates all the strings in the iterable. The output will be 'HelloWorld!'
, which is the concatenated version of the strings.
Conclusion
In this tutorial, you learned how to use Python’s sum()
function to efficiently sum numeric values and concatenate sequences. You also explored a couple of alternative tools for summing and concatenating objects. This knowledge will help you solve summation problems in your code more efficiently and effectively.
Now you have a solid understanding of Python’s sum()
function and its various use cases. You can confidently use sum()
and its alternatives to efficiently compute sums and concatenate sequences in your Python programs.