Пропустить до содержимого

Как использовать и исправить функцию суммирования в 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:

numbers = [1, 2, 3, 4, 5]
total = 0
for number in numbers:
total += number
print(total)

Here, you first create total and initialize it to 0. Then, using a for loop, you iterate over each number in the list numbers and add it to the total variable. Finally, you print out the value of total, which gives you the sum of all the numbers in the list.

Getting Started With Python’s sum()

Python’s built-in sum() function simplifies the process of summing numeric values. It takes an iterable, such as a list, tuple, or set, and returns the summation of all the values in the iterable.

The Required Argument: iterable

The sum() function has one required argument, which is the iterable that contains the values you want to sum. You can pass any iterable to sum(), such as a list, tuple, set, or even a string.

numbers = [1, 2, 3, 4, 5]
result = sum(numbers)
print(result)

In this example, you have a list of numbers [1, 2, 3, 4, 5]. You pass this list as an argument to the sum() function, which returns the sum of all the numbers in the list. The result is then printed out, giving you the output 15.

The Optional Argument: start

The sum() function also has an optional second argument, which is the start value. This argument is used to initialize the summing process with a specific value, instead of the default 0.

numbers = [1, 2, 3, 4, 5]
result = sum(numbers, 10)
print(result)

In this example, you pass the list of numbers [1, 2, 3, 4, 5] as the first argument to sum(), and the integer 10 as the second argument. The sum() function then starts the summing process by adding the start value 10 to the first number in the list, followed by the remaining numbers. The result is then printed out, giving you the output 25.

Summing Numeric Values

One of the most common use cases for the sum() function is summing numeric values. You can pass a list of numbers to sum() and it will compute the sum of all the numbers for you.

numbers = [1, 2, 3, 4, 5]
result = sum(numbers)
print(result)

In this example, you have a list of numbers [1, 2, 3, 4, 5]. You pass this list as an argument to the sum() function, which returns the sum of all the numbers in the list. The result is then printed out, giving you the output 15.

Concatenating Sequences

Another interesting use case for the sum() function is concatenating sequences, such as lists and tuples. You can pass a list of lists or a tuple of tuples to sum(), and it will concatenate them for you.

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = sum(data, [])
print(result)

In this example, you have a list of lists [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. You pass this list as the first argument to the sum() function, and an empty list [] as the second argument. The sum() function then concatenates all the sublists together, giving you the output [1, 2, 3, 4, 5, 6, 7, 8, 9].

Practicing With Python’s sum()

Now that you have an understanding of how to use the sum() function, let’s practice by solving some common summation problems.

Computing Cumulative Sums

One common problem is computing the cumulative sum of a list of numbers. The cumulative sum at each index i is the sum of all the numbers from index 0 to index i.

numbers = [1, 2, 3, 4, 5]
cumulative_sums = [sum(numbers[:i+1]) for i in range(len(numbers))]
print(cumulative_sums)

In this example, you have a list of numbers [1, 2, 3, 4, 5]. The list comprehension iterates over the indices of the list, from 0 to len(numbers)-1. For each index i, it slices the list up to index i+1, and passes this slice to the sum() function to compute the cumulative sum. The result is a new list [1, 3, 6, 10, 15], which represents the cumulative sums of the original list.

Calculating the Mean of a Sample

Another common problem is calculating the mean of a sample, which is the average value of all the numbers in the sample.

numbers = [1, 2, 3, 4, 5]
mean = sum(numbers) / len(numbers)
print(mean)

In this example, you have a list of numbers [1, 2, 3, 4, 5]. You pass this list as an argument to the sum() function to compute the sum of all the numbers. Then, you divide the sum by the length of the list using the / operator to get the mean value. The result is the output 3.0, which is the mean of the sample.

Finding the Dot Product of Two Sequences

The dot product of two sequences is the sum of the products of corresponding elements in the sequences. You can use the zip() function to pair up the elements from two lists, and then pass the pairs to the sum() function to compute the dot product.

a = [1, 2, 3]
b = [4, 5, 6]
dot_product = sum(x * y for x, y in zip(a, b))
print(dot_product)

In this example, you have two lists [1, 2, 3] and [4, 5, 6]. The zip() function pairs up the elements from both lists, giving you the pairs [(1, 4), (2, 5), (3, 6)]. The list comprehension iterates over each pair (x, y) and multiplies them together using the * operator. Finally, the sum() function computes the sum of all the products, giving you the output 32, which is the dot product of the two sequences.

Flattening a List of Lists

Flattening a list of lists means converting a list that contains sublists into a single flat list that contains all the elements from the sublists. One way to do this is by using the sum() function with an empty list as the start value.

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = sum(data, [])
print(flattened)

In this example, you have a list of lists [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. You pass this list as the first argument to the sum() function, and an empty list [] as the second argument. The sum() function then concatenates all the sublists together, giving you the output [1, 2, 3, 4, 5, 6, 7, 8, 9], which is the flattened list.

Using Alternatives to sum()

While sum() is a convenient and Pythonic way to sum values, there are alternative tools that you can use in specific situations.

Summing Floating-Point Numbers: math.fsum()

If you’re working with floating-point numbers and need a more accurate result, you can use the math.fsum() function from the math module. math.fsum() provides a more precise way to sum floating-point numbers by using a different algorithm.

import math
numbers = [1.1, 2.2, 3.3, 4.4, 5.5]
result = math.fsum(numbers)
print(result)

In this example, you have a list of floating-point numbers [1.1, 2.2, 3.3, 4.4, 5.5]. You import the math module and then use the math.fsum() function to compute the sum of all the floating-point numbers. The result is the output 16.5, which is the more accurate sum of the numbers.

Concatenating Iterables With itertools.chain()

If you need to concatenate multiple iterables, such as lists, tuples, or sets, you can use the itertools.chain() function. itertools.chain() takes multiple iterables as arguments and returns a single iterator that produces all the elements from the input iterables.

import itertools
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
result = list(itertools.chain(a, b, c))
print(result)

In this example, you have three lists [1, 2, 3], [4, 5, 6], and [7, 8, 9]. You import the itertools module and then use the itertools.chain() function to concatenate all three lists together. The result is the output [1, 2, 3, 4, 5, 6, 7, 8, 9], which is the flattened list of all the elements from the input lists.

Concatenating Strings With str.join()

If you need to concatenate multiple strings into a single string, you can use the str.join() method. str.join() is a string method that takes an iterable of strings and concatenates them using the specified separator.

words = ["Hello", "World", "Python"]
result = " ".join(words)
print(result)

In this example, you have a list of words ["Hello", "World", "Python"]. You call the str.join() method on the separator string " ", which means to concatenate the words with a space in between. The result is the output "Hello World Python", which is the single string that contains all the words separated by spaces.

Conclusion

In this tutorial, you learned how to use Python’s sum() function to easily sum lists of numeric values and concatenate sequences. You also explored some common summation problems and alternative tools for specific use cases. Armed with this knowledge, you can now efficiently handle summation problems in your code using the Pythonic way with sum() or other specialized tools.