Skip to content

Python Sum List: Effortlessly Calculate the Sum of a List

[

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
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 total. Finally, you print the value of total, which is the sum of all the numbers.

While this method works, it can be a bit cumbersome and repetitive. Fortunately, Python provides a built-in function called sum() that can simplify this whole process.

Getting Started With Python’s sum()

Python’s sum() function is a powerful tool for summing numeric values. It can take an iterable (such as a list, tuple, or set) of numbers and add them together to give you a single value.

The basic syntax for using sum() looks like this:

sum(iterable, start=0)

iterable is a required argument and should be a sequence of numbers that you want to sum. start is an optional argument that specifies the initial value of the sum. If start is not provided, it defaults to 0.

Let’s take a closer look at each of these arguments.

The Required Argument: iterable

The iterable argument is the sequence of numbers that you want to sum. It can be any iterable object, such as a list, tuple, set, or even a string.

For example, you can pass a list of numbers to sum() like this:

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

Here, numbers is the iterable object that contains the numbers you want to sum. You pass this iterable to sum() as the first argument, and it returns the total sum of the numbers.

The Optional Argument: start

The start argument is an optional value that specifies the initial value of the sum. If you don’t provide a value for start, it defaults to 0.

You can specify a different start value by passing it as the second argument to sum(), like this:

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

In this example, start is set to 10, so the sum starts at 10 instead of 0. The numbers in the numbers list are then added to the starting value, giving you the total sum.

Summing Numeric Values

Using sum() to sum a list of numbers is pretty straightforward. You simply pass the list as the iterable argument, and sum() will return the sum of all the numbers.

For example, let’s say you have a list of numbers like this:

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

When you run this code, the value of total will be 15, which is the sum of all the numbers in the list.

Concatenating Sequences

An interesting and lesser-known use case of sum() is concatenating lists and tuples. When you pass a sequence of lists or tuples to sum(), it will concatenate them together into a single sequence.

Here’s an example:

lists = [[1, 2], [3, 4], [5, 6]]
concatenated = sum(lists, [])
concatenated

In this example, lists is a list of lists. By passing lists as the iterable argument to sum(), and specifying an empty list [] as the start value, sum() will concatenate all the lists in lists into a single list.

The value of concatenated will be [1, 2, 3, 4, 5, 6], which is the concatenation of all the lists in lists.

This can be a useful technique when you need to flatten a list of lists or concatenate multiple sequences together.

Practicing With Python’s sum()

Now that you know the basics of using sum(), let’s practice with some more examples to solidify your understanding.

Computing Cumulative Sums

One useful application of sum() is computing cumulative sums. A cumulative sum is the sum of all the previous numbers in a sequence.

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

In this example, the numbers list contains the numbers you want to compute the cumulative sums of. The cumulative_sums list starts out empty.

Using a for loop, you iterate over the range of indices of the numbers list. For each index i, you slice the numbers list up to index i+1 (using the numbers[:i+1] syntax) and pass it to sum() to compute the cumulative sum.

The resulting cumulative sums are then appended to the cumulative_sums list.

At the end, the value of cumulative_sums will be [1, 3, 6, 10, 15], which is the cumulative sum of all the numbers in the numbers list.

Calculating the Mean of a Sample

Another common task is computing the mean (average) of a sample. The mean is calculated by dividing the sum of all the numbers in the sample by the number of elements in the sample.

Here’s how you can compute the mean of a sample using sum():

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

In this example, sample is the list of numbers you want to compute the mean of. You pass sample to sum() to get the sum of all the numbers, and then divide the sum by the length of sample to get the mean.

The value of mean will be 3.0, which is the mean of all the numbers in the sample.

Finding the Dot Product of Two Sequences

The dot product of two sequences is a mathematical operation that takes two vectors (sequences of numbers) and returns a scalar (single number). It’s calculated by multiplying corresponding elements of each sequence and then summing up the products.

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

In this example, vector1 and vector2 are two sequences of numbers (vectors) that you want to compute the dot product of. You use the zip() function to pair up corresponding elements of the two vectors, and then multiply each pair of elements together using a generator expression (x * y for x, y in zip(vector1, vector2)). Finally, you pass the generator expression to sum() to get the dot product.

The value of dot_product will be 32, which is the dot product of vector1 and vector2.

Flattening a List of Lists

As mentioned earlier, you can use sum() to concatenate lists together. This can be especially useful when you have a list of lists and want to flatten it into a single list.

lists = [[1, 2], [3, 4], [5, 6]]
flattened = sum(lists, [])
flattened

In this example, lists is a list of lists that you want to flatten. By passing lists as the iterable argument to sum() and specifying an empty list [] as the start value, sum() will concatenate all the lists in lists into a single list.

The value of flattened will be [1, 2, 3, 4, 5, 6], which is the flattened version of lists.

Using Alternatives to sum()

While sum() is a powerful tool for summing numeric values and concatenating sequences, there are some alternative functions and techniques you can use depending on the specific requirements of your code.

Summing Floating-Point Numbers: math.fsum()

If you’re working with floating-point numbers and require higher precision in the sum, you can use the math.fsum() function instead of sum().

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

The math.fsum() function provides a more accurate sum for floating-point numbers by using a different algorithm than sum(). The value of total in this example will be 0.6, which is the more precise sum of the floating-point numbers in the numbers list.

Concatenating Iterables With itertools.chain()

If you need to concatenate multiple iterables (not just lists and tuples), you can use the itertools.chain() function instead of sum().

import itertools
iterable1 = [1, 2, 3]
iterable2 = [4, 5, 6]
concatenated = list(itertools.chain(iterable1, iterable2))
concatenated

In this example, iterable1 and iterable2 are two different iterables that you want to concatenate. You use itertools.chain() to chain them together, and then convert the result to a list using list().

The value of concatenated will be [1, 2, 3, 4, 5, 6], which is the concatenation of iterable1 and iterable2.

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 instead of sum().

strings = ["Hello", "world", "!"]
concatenated = "".join(strings)
concatenated

In this example, strings is a list of strings that you want to concatenate. You use the str.join() method to join the strings together, specifying an empty string "" as the separator.

The value of concatenated will be "Hello world!", which is the concatenation of all the strings in strings.

Conclusion

In this tutorial, you’ve learned about Python’s sum() function and how it can be used to efficiently sum numeric values and concatenate sequences. You’ve seen how to use sum() to solve common summation problems, compute cumulative sums, calculate the mean of a sample, find the dot product of sequences, and flatten a list of lists. You’ve also explored some alternative tools and techniques for summing and concatenating objects.

With this knowledge, you’ll be able to approach and solve summation problems in your code more efficiently using Python’s built-in sum() function or other specialized tools.