Skip to content

Easily Understand and Use the Sum Function in 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, you iterate over each number in the list using a for loop and add each number to the total variable. Finally, you print the value of total, which will be the sum of all the numbers.

This approach works fine, but Python provides a built-in function sum() that simplifies the task of summing a list of numbers.

Getting Started With Python’s sum()

Python’s sum() function takes an iterable as its required argument and returns the sum of all the values in the iterable. An iterable can be any object that can be looped over.

The Required Argument: iterable

Let’s start by looking at how to use sum() with the required argument, iterable. An iterable can be a list, tuple, set, or any other object that can be iterated over.

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

In this example, you pass the list numbers as the argument to sum(). The function iterates over each element in the list and adds them together, returning the sum as the result. This simplifies the process of summing a list of numbers to a single line of code.

The Optional Argument: start

In addition to the required argument iterable, the sum() function also has an optional argument called start. The start argument allows you to specify a value that will be added to the sum of the iterable. By default, start is set to 0.

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

In this example, you specify start=10 as the second argument to sum(). This means that the sum of numbers will be calculated and then 10 will be added to the result. The final sum will be 25 (15 + 10).

Using the start argument can be useful if you need to add a constant value to the sum of an iterable.

Summing Numeric Values

In addition to summing a list of numbers, you can use sum() to sum other types of numeric values. For example, you can sum a range of numbers by passing the range() function as the argument to sum().

total = sum(range(1, 101))
print(total)

In this example, you pass range(1, 101) as the argument to sum(). This creates a range of numbers from 1 to 100 (inclusive) and calculates the sum of all the numbers. The result is 5050.

The sum() function can handle large ranges of numbers efficiently, so you don’t have to worry about performance issues when summing a large number of values.

Concatenating Sequences

In addition to summing numeric values, you can also concatenate sequences using sum().

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

In this example, you have a sequence of lists [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. You pass this sequence as the argument to sum() and provide an empty list [] as the start argument.

By default, sum() treats the items in the sequence as numbers and adds them together. But when you provide an empty list as the start argument, sum() realizes that you want to concatenate the lists instead of adding them. It then concatenates the lists in the sequence into a single list.

The result is a flattened list [1, 2, 3, 4, 5, 6, 7, 8, 9].

Concatenating sequences using sum() can be convenient when you need to flatten a list of lists or concatenate multiple lists into a single list.

Practicing With Python’s sum()

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

Computing Cumulative Sums

You can use sum() to compute the cumulative sum of a sequence of numbers. The cumulative sum of a sequence is the sum of all the previous numbers plus the current number.

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 use a combination of list comprehension and sum() to calculate the cumulative sums of the numbers in the list.

You iterate over the range of numbers from 0 to the length of numbers using a for loop. In each iteration, you slice the list numbers from the beginning up to the current index i and pass it to sum() to calculate the sum. The result is a list of cumulative sums [1, 3, 6, 10, 15].

Calculating cumulative sums can be useful in various scenarios, such as financial calculations or analyzing time series data.

Calculating the Mean of a Sample

You can also use sum() to calculate the mean (average) of a sample of numbers.

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

In this example, you first calculate the sum of the numbers using sum() and then divide the result by the length of the numbers to get the mean value. The result is 3.0.

Calculating the mean is a common statistical operation, and using sum() simplifies the process by handling the summation part automatically.

Finding the Dot Product of Two Sequences

In linear algebra, the dot product is a binary operation that takes two equal-length sequences of numbers and returns a single number. You can use sum() to calculate 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 use a combination of zip() and sum() to calculate the dot product of sequence1 and sequence2.

zip() takes two or more sequences and returns an iterator of tuples, where each tuple contains the corresponding elements from the input sequences. You then use a generator expression (x * y for x, y in zip(sequence1, sequence2)) to calculate the element-wise product of the two sequences.

Finally, you pass the generator expression to sum() to calculate the sum of all the products.

The result is the dot product of sequence1 and sequence2, which is 32 (1 * 4 + 2 * 5 + 3 * 6).

Calculating the dot product of two sequences is a fundamental operation in linear algebra and can be useful in various applications, such as machine learning and physics simulations.

Flattening a List of Lists

You can also use sum() to flatten a list of lists into a single list.

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

In this example, you pass the list_of_lists as the argument to sum() and provide an empty list [] as the start argument.

sum() iterates over the elements in list_of_lists and concatenates them into a single list. The result is a flattened list [1, 2, 3, 4, 5, 6, 7, 8, 9].

Flattening a list of lists can be useful when you’re working with nested data structures or when you need to convert a multi-dimensional array into a one-dimensional array.

Using Alternatives to sum()

While sum() is a convenient and efficient tool for summing values in Python, there are also alternative functions and methods that you can use depending on your specific needs.

Summing Floating-Point Numbers: math.fsum()

If you’re summing a large number of floating-point numbers and need high precision, you can use the math.fsum() function instead of sum().

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

In this example, you import the math module and use its fsum() function to sum the floating-point numbers in the list. fsum() provides higher precision compared to sum() when working with floating-point numbers.

Concatenating Iterables With itertools.chain()

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

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

In this example, you import the itertools module and use its chain() function to concatenate iterable1 and iterable2. chain() takes multiple iterables as arguments and returns an iterator that yields elements from each iterable in sequence.

You can then convert the iterator to a list using the list() function to get the concatenated iterables as a list.

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_string = ''.join(strings)
print(concatenated_string)

In this example, you use the join() method of strings to concatenate the strings in the list. You pass an empty string '' as the separator between the strings, so they are joined together without any separation.

The result is the concatenated string 'HelloWorld!'.

Using str.join() is a more Pythonic way to concatenate strings compared to using sum().

Conclusion

Python’s sum() function is a powerful tool for summing numeric values and concatenating sequences. It provides a simple and efficient way to solve summation problems in your code.

In this tutorial, you learned how to use sum() with different arguments to sum numeric values, concatenate lists and tuples, and solve various summation-related problems. You also explored alternatives to sum() for specific use cases.

Now you have a good understanding of how to use sum() in Python. Keep in mind that understanding the summation problem and selecting the appropriate tool for the task are crucial for writing efficient and concise code.