Как использовать функцию sum в 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.
In this tutorial, you’ll learn how to:
- Sum numeric values by hand using general techniques and tools
- Use Python’s
sum()
to add several numeric values efficiently - Concatenate lists and tuples with
sum()
- Use
sum()
to approach common summation problems - Use appropriate values for the arguments in
sum()
- Decide between
sum()
and alternative tools to sum and concatenate objects
This knowledge will help you efficiently approach and solve summation problems in your code using either sum()
or other alternative and specialized tools.
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:
In this case, you initialize the total
to 0, and then use a for
loop to iterate over each number in the list. Inside the loop, you add each number to the total
using the +=
operator. Finally, you print the total
to get the sum of the numbers.
Getting Started with Python’s sum()
Python’s built-in sum()
function provides a much simpler and more concise way to sum a list of numeric values. The sum()
function takes two arguments: iterable
and start
.
The Required Argument: iterable
The iterable
argument is the only required argument for the sum()
function. It is an iterable object, such as a list, tuple, or range, that contains the values you want to sum.
In this example, you pass the numbers
list as the iterable
argument to the sum()
function. The sum()
function then adds up all the numbers in the list and returns the total sum.
The Optional Argument: start
The start
argument is an optional argument for the sum()
function. It is a numeric value that you can use to start the summation process. By default, the start
argument is set to 0.
In this example, you pass the numbers
list as the iterable
argument and set the start
argument to 10. The sum()
function then starts the summation process from 10 instead of 0, and adds up all the numbers in the list to get the total sum. The result in this case would be 25.
By using the start
argument, you can easily customize where the summation process should start from.
Summing Numeric Values
Python’s sum()
function is particularly useful for summing numeric values. It can handle both integers and floating-point numbers.
In this example, the numbers
list contains integers, and the sum()
function returns the total sum of all the integers in the list.
Python’s sum()
function can also handle floating-point numbers in the same way.
In this example, the numbers
list contains floating-point numbers, and the sum()
function returns the total sum of all the floating-point numbers in the list.
Python’s sum()
function can handle both integers and floating-point numbers, making it a versatile tool for summing numeric values.
Concatenating Sequences
In addition to summing numeric values, Python’s sum()
function can also concatenate sequences. This can be useful when you have a list of lists or a list of tuples that you want to flatten into a single list.
In this example, the lists
list contains three sublists. By passing an empty list as the start
argument, you can concatenate all the sublists into a single list. The result is the flattened
list, which contains all the elements from the sublists.
Python’s sum()
function can be a convenient tool for flattening nested lists or tuples into a single list.
Practicing With Python’s sum()
Now that you have a good understanding of the basics of Python’s sum()
function, let’s practice using it in various scenarios.
Computing Cumulative Sums
One common use case for the sum()
function is computing cumulative sums. A cumulative sum is the sum of all values up to a certain point in a sequence.
In this example, you use a list comprehension to iterate over the indices of the numbers
list. For each index, you slice the numbers
list up to that index and pass it as the iterable
argument to the sum()
function. The result is a list of cumulative sums, where each element is the sum of all values up to that point in the numbers
list.
Calculating the Mean of a Sample
You can also use Python’s sum()
function to calculate the mean of a sample. The mean is the average value of a set of numbers.
In this example, you sum all the numbers in the numbers
list using the sum()
function, and then divide the sum by the number of elements in the list to get the mean.
Finding the Dot Product of Two Sequences
The dot product of two sequences is a mathematical operation that calculates the sum of the products of corresponding elements in the sequences. Python’s sum()
function can be used to compute the dot product of two sequences.
In this example, you use a generator expression with the zip()
function to iterate over corresponding elements of the vector1
and vector2
lists. For each pair of elements, you multiply them together and pass the result to the sum()
function. The result is the dot product of the two sequences.
Flattening a List of Lists
As mentioned earlier, Python’s sum()
function can be used to flatten a list of lists into a single list.
In this example, you pass the lists
list as the iterable
argument to the sum()
function, along with an empty list as the start
argument. The result is the flattened
list, which contains all the elements from the sublists.
Using Alternatives to sum()
While Python’s sum()
function is a powerful and convenient tool for summing values and concatenating sequences, there are also alternative functions and tools that you can use in specific scenarios.
Summing Floating-Point Numbers: math.fsum()
If you need to sum a large number of floating-point numbers with high precision, you can use Python’s math.fsum()
function instead of sum()
.
In this example, the numbers
list contains 0.1 repeated 10 times. If you use the sum()
function to sum these numbers, you might get a result that is not exactly equal to 1 due to floating-point precision limitations. However, if you use the math.fsum()
function instead, you can get a more accurate result.
Concatenating Iterables With itertools.chain()
If you want to concatenate multiple iterables, such as lists, tuples, or range objects, you can use Python’s itertools.chain()
function.
In this example, you use the itertools.chain()
function to concatenate the list1
, list2
, and list3
lists into a single list. The result is the concatenated
list, which contains all the elements from the input lists.
Concatenating Strings With str.join()
If you want to concatenate strings, you can use Python’s str.join()
method.
In this example, the words
list contains two strings, “Hello” and “World”. By calling the str.join()
method on the space character ” ”, you can concatenate the strings in the words
list with a space between them. The result is the sentence
string, which contains the concatenated words.
Conclusion
Python’s sum()
function is a powerful and versatile tool that can be used to efficiently sum numeric values and concatenate sequences. Whether you need to sum a list of numbers, concatenate lists of lists, or solve more complex summation problems, sum()
can be a handy tool in your Python toolkit.
In this tutorial, you learned how to use sum()
to sum numeric values, concatenate sequences, compute cumulative sums, calculate the mean of a sample, find the dot product of two sequences, and flatten a list of lists. You also explored alternative functions and tools, such as math.fsum()
, itertools.chain()
, and str.join()
, that can be used in specific scenarios.
By leveraging Python’s built-in functions and tools, you can write more efficient and concise code that is easier to understand and maintain. So go ahead and start using sum()
in your Python projects to make your code more Pythonic!