Skip to content

Effortlessly Master Python's Sum Function

[

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:

Python

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, you use a for loop to iterate over each number in the numbers list. On each iteration, you add the current number to the total variable. Finally, you get the sum by printing the value of total.

While this custom solution works fine, Python provides a built-in function called sum() that simplifies this process.

Getting Started With Python’s sum()

Python’s built-in function sum() allows you to sum a list of numeric values in a concise and efficient manner. The basic syntax for using sum() is as follows:

sum(iterable, start)

Here, iterable is a required argument that represents the sequence or collection of numbers you want to sum. It can be any iterable object, such as a list, tuple, or range. The start argument is an optional parameter that specifies the value to start the summation with. If start is not provided, the default value is 0.

Let’s take a closer look at these two arguments.

The Required Argument: iterable

The iterable argument is the sequence of numbers you want to sum. It can be either a list, a tuple, or any other iterable object.

Here’s an example:

Python

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

Output:

15

In this example, you pass the numbers list to the sum() function, and it returns the sum of all the values in the list.

The Optional Argument: start

The start argument is an optional parameter that specifies the value to start the summation with. If you don’t provide a value for start, the default is 0.

Here’s an example:

Python

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

Output:

25

In this example, you pass the numbers list to the sum() function and also provide a value of 10 for the start parameter. The sum() function adds the numbers in the list, starting from 10, and returns the final sum of 25.

By using the start parameter, you have the flexibility to choose the initial value for the summation.

Summing Numeric Values

So far, you’ve learned the basics of using the sum() function to sum a list of numeric values. But what about other data types that are not numbers? What happens when you use sum() with strings or other non-numeric objects?

When you try to apply sum() to a sequence of non-numeric objects, you’ll encounter an error. This is because the + operator used by sum() is not defined for non-numeric types.

Python

words = ['Hello', 'World']
total = sum(words)
total

Output:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

In this example, you have a list of strings words. When you try to use sum() on this list, Python raises a TypeError because you can’t concatenate strings using the + operator.

To sum non-numeric objects or sequences, you need to use other methods or functions that are appropriate for the specific data type.

Concatenating Sequences

One interesting and useful feature of Python’s sum() function is its ability to concatenate sequences. This can be handy when you want to flatten a list of lists or concatenate multiple strings.

Let’s see some examples:

Python

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

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

In this example, you have a list of lists nested_lists. By passing an empty list as the start parameter, the sum() function concatenates all the sublists into a single flattened list.

Python

strings = ['Hello', ' ', 'World', '!']
message = sum(strings, '')
message

Output:

'Hello World!'

In this example, you have a list of strings strings. By passing an empty string as the start parameter, the sum() function concatenates all the strings together into a single message.

By using sum() with non-numeric sequences, you can conveniently concatenate and flatten lists or strings.

Practicing With Python’s sum()

Now that you understand the basics of sum() and how to use it to sum numeric values or concatenate sequences, let’s explore some common summation problems and practice with the sum() function.

Computing Cumulative Sums

One common use case for sums is computing cumulative sums. A cumulative sum is the sum of a sequence of numbers up until a certain position.

Let’s say you have a list of numbers [1, 2, 3, 4, 5] and you want to compute the cumulative sum at each position. Here’s how you can do it:

Python

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

Output:

[1, 3, 6, 10, 15]

In this example, you use a for loop to iterate over each number in the numbers list. On each iteration, you add the current number to the total variable and append the cumulative sum to the cumulative_sums list.

While this custom solution works fine, you can achieve the same result more concisely using the sum() and list comprehension:

Python

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

Output:

[1, 3, 6, 10, 15]

In this example, you use list comprehension to iterate over the indices of the numbers list. For each index, you slice the numbers list up to that index (including the current number) and pass it to the sum() function to compute the cumulative sum.

This approach is more concise and simpler to read than using a for loop.

Calculating the Mean of a Sample

Another common problem is calculating the mean of a sample. The mean is the average value of a set of numbers. In statistics, it’s usually represented by the symbol x̄.

To calculate the mean, you need to sum all the numbers and divide the sum by the total count of numbers.

Here’s how you can do it manually using a for loop:

Python

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

Output:

3.0

In this example, you sum all the numbers in the numbers list using sum(), get the count of numbers using len(), and then calculate the mean by dividing the total sum by the count.

Similarly to computing cumulative sums, you can achieve the same result in a more concise way using list comprehension and the mean() function from the statistics module:

Python

import statistics
numbers = [1, 2, 3, 4, 5]
mean = statistics.mean(numbers)
mean

Output:

3.0

In this example, you import the statistics module and use the mean() function to calculate the mean of the numbers list.

Using the built-in sum() function in combination with other modules or functions, you can solve various statistical problems efficiently.

Finding the Dot Product of Two Sequences

In linear algebra, the dot product is a common operation between two vectors or sequences of numbers. The dot product of two vectors is a scalar value that represents the sum of the products of corresponding elements in the vectors.

To calculate the dot product of two sequences, you can use the sum() function in combination with list comprehension:

Python

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

Output:

32

In this example, you use the zip() function to pair each element in vector1 with the corresponding element in vector2. Then, you use list comprehension to multiply each pair of elements and create a new list. Finally, you pass this new list to the sum() function to get the dot product.

Conclusion

In this tutorial, you learned how to use Python’s sum() function to sum a list of numeric values or concatenate sequences. The sum() function is a powerful tool that simplifies computations and allows you to solve a variety of summation problems efficiently.

By understanding the basics of sum() and knowing how to use it with appropriate arguments, you can confidently approach and solve summation problems in your code.

Additionally, you practiced with various examples of how to use sum() to compute cumulative sums, calculate means, find dot products, and more. This gives you a solid foundation for utilizing sum() in different contexts.

Whether you’re working on mathematical computations, statistics, or even when you need to flatten nested lists or concatenate strings, Python’s sum() function is a handy tool to have in your programming arsenal.