Skip to content

Effortlessly Master Python Summation

[

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:

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, you use a for loop to iterate over each number in the numbers list. For each iteration, you add the number to the total. Finally, you print out the total to get the sum of all the numbers.

While this solution works, Python provides a more concise and efficient way to sum values: the sum() function.

Getting Started With Python’s sum()

The sum() function in Python takes in an iterable object as its required argument and returns the sum of all the items in that iterable. Let’s take a look at how it works.

The Required Argument: iterable

The iterable argument is required by the sum() function, and it represents the object that you want to calculate the sum for. This object can be a list, tuple, or any other iterable.

my_list = [1, 2, 3, 4, 5]
total = sum(my_list)
print(total)

In this example, you create a list called my_list with some numeric values. You then pass this list as the argument to the sum() function, and it returns the sum of all the numbers in the list. Finally, you print the total to see the result.

The Optional Argument: start

The sum() function also accepts an optional argument called start. This argument represents the value that is added to the sum of the items in the iterable. By default, start is set to 0.

my_list = [1, 2, 3, 4, 5]
total = sum(my_list, start=10)
print(total)

In this example, you pass the start argument with a value of 10 to the sum() function. This means that the sum of the items in the list will be calculated starting from 10. Therefore, the result will be the sum of the numbers in the list (15) plus the start value (10), giving you a total of 25.

Summing Numeric Values

Now that you know how to use the sum() function, let’s explore some more examples of summing numeric values.

Example 1: Summing a List of Numbers

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

In this example, you have a list of numbers and you want to get the sum of all the numbers. You pass the numbers list as the argument to the sum() function, and it returns the sum of all the numbers in the list. The result, in this case, will be 15.

Example 2: Summing a Tuple of Numbers

numbers = (1, 2, 3, 4, 5)
total = sum(numbers)
print(total)

In this example, you have a tuple of numbers and you want to get the sum of all the numbers. You pass the numbers tuple as the argument to the sum() function, and it returns the sum of all the numbers in the tuple. The result will be the same as in the previous example: 15.

Example 3: Summing a Range of Numbers

start = 1
end = 5
numbers = range(start, end+1)
total = sum(numbers)
print(total)

In this example, you have a start value of 1 and an end value of 5. You use the range() function to create a range of numbers from 1 to 5 (inclusive). Then, you pass this range as the argument to the sum() function, which returns the sum of all the numbers in the range. The result will be 15, just like in the previous examples.

Concatenating Sequences

In addition to summing numeric values, you can also use sum() to concatenate sequences, such as lists and tuples. This can be useful when you have a list of lists and you want to flatten it into a single list.

lists = [[1, 2, 3], [4, 5], [6, 7, 8]]
flattened_list = sum(lists, [])
print(flattened_list)

In this example, you have a list of lists called lists, and you want to flatten it into a single list. You pass the lists as the argument to the sum() function, along with an empty list [] as the start value. The sum() function then concatenates all the lists in lists into a single list and returns the result. The flattened_list will be [1, 2, 3, 4, 5, 6, 7, 8].

Practicing With Python’s sum()

Now that you have a good understanding of how to use Python’s sum() function, let’s practice with some more examples.

Computing Cumulative Sums

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

In this example, you have a list of numbers and you want to compute the cumulative sum for each number in the list. You initialize an empty list called cumulative_sums to store the cumulative sums. Then, you use a for loop and the sum() function to calculate the cumulative sum at each index of the numbers list. Finally, you append each cumulative sum to the cumulative_sums list and print the result.

The result will be a list of cumulative sums: [1, 3, 6, 10, 15].

Calculating the Mean of a Sample

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

In this example, you have a list of numbers and you want to calculate the mean (average) of the sample. You use the sum() function to get the sum of all the numbers in the list, and then divide it by the length of the list to get the mean. The result will be the mean of the sample: 3.0.

Finding the Dot Product of Two Sequences

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

In this example, you have two sequences: sequence1 and sequence2. You want to calculate the dot product of these two sequences. You use a generator expression, x * y for x, y in zip(sequence1, sequence2), to multiply each pair of corresponding elements from the two sequences. Then, you pass this generator expression as the argument to the sum() function, which calculates the sum of all the products. The result will be the dot product of the two sequences: 32.

Flattening a List of Lists

lists = [[1, 2, 3], [4, 5], [6, 7, 8]]
flattened_list = sum(lists, [])
print(flattened_list)

As mentioned earlier, you can use the sum() function to flatten a list of lists. In this example, you have a list of lists called lists, and you want to flatten it into a single list. You pass the lists as the argument to the sum() function, along with an empty list [] as the start value. The sum() function concatenates all the lists in lists into a single list and returns the result. The flattened_list will be [1, 2, 3, 4, 5, 6, 7, 8].

Using Alternatives to sum()

While the sum() function is a powerful tool for summing values and concatenating sequences, there are also alternative functions and tools available for specific use cases.

Summing Floating-Point Numbers: math.fsum()

If you are working with floating-point numbers and require precise results, you can use the math.fsum() function instead of sum(). The math.fsum() function is more accurate for floating-point arithmetic, especially when dealing with a large number of floating-point values.

import math
numbers = [0.1, 0.1, 0.1, 0.1, 0.1]
total = math.fsum(numbers)
print(total)

In this example, you have a list of floating-point numbers, and you want to get the sum of all the numbers. You import the math module, which provides the fsum() function for precise floating-point arithmetic. Then, you pass the numbers list as the argument to the math.fsum() function, and it returns the accurate sum of all the numbers in the list. The result will be 0.5.

Concatenating Iterables With itertools.chain()

If you need to concatenate multiple iterables other than lists and tuples, you can use the itertools.chain() function from the itertools module. The itertools.chain() function takes in one or more iterables as arguments and returns an iterator that produces the elements of each iterable in order.

import itertools
iterable1 = [1, 2, 3]
iterable2 = (4, 5, 6)
iterable3 = {7, 8, 9}
concatenated_iterable = list(itertools.chain(iterable1, iterable2, iterable3))
print(concatenated_iterable)

In this example, you have three different iterables: iterable1, iterable2, and iterable3. You want to concatenate these iterables into a single list. You import the itertools module, which provides the chain() function for concatenating iterables. Then, you pass the three iterables as arguments to the itertools.chain() function, followed by the list() function to convert the iterator into a list. The concatenated_iterable will be [1, 2, 3, 4, 5, 6, 7, 8, 9].

Concatenating Strings With str.join()

If you have a list of strings that you want to concatenate into a single string, you can use the str.join() method. The str.join() method takes in an iterable of strings and returns a new string that is the concatenation of all the strings in the iterable, with the specified separator between them.

strings = ["Hello", "World", "!"]
concatenated_string = " ".join(strings)
print(concatenated_string)

In this example, you have a list of strings called strings, and you want to concatenate them into a single string. You use the str.join() method with a space " " as the separator between the strings. The join() method joins all the strings in the strings list with a space between them and returns the concatenated string. The concatenated_string will be “Hello World !“.

Conclusion

In this tutorial, you have learned how to use Python’s sum() function to efficiently sum a list of numeric values and concatenate sequences. You have seen examples of summing numeric values, flattening a list of lists, and using alternative functions and tools. These techniques will help you approach and solve summation problems in your code using either sum() or other alternative and specialized tools.

Remember to use the appropriate values for the arguments in sum() and choose between sum() and alternative tools based on your specific use case. Whether you’re summing numbers, concatenating sequences, or solving other summation problems, Python provides powerful and efficient tools to make your coding tasks easier and more Pythonic.