Skip to content

Effortlessly Learn How to Use Python sum Function

[

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 through each number in the numbers list and add it to the total variable. Finally, you print the total, which should give you the sum of all the numbers.

While this approach works, it requires you to write quite a bit of code, especially if you have large lists or need to sum numbers in multiple places throughout your program. This is where Python’s sum() function comes in handy.

Getting Started With Python’s sum()

Python’s sum() function is a built-in function that allows you to sum a list of numbers or concatenate sequences. It’s designed to be efficient and Pythonic, meaning it follows the principles of simplicity and readability that Python emphasizes.

The Required Argument: iterable

The sum() function takes at least one required argument, iterable, which should be an iterable object containing the numbers or sequences you want to sum. An iterable object is any object that can be iterated over, such as a list, tuple, string, or even a range of numbers.

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

Output:

15

In this example, you pass the list of numbers directly to the sum() function. It iterates over each item in the list and adds them together, giving you the total sum.

The Optional Argument: start

The sum() function also accepts an optional second argument, start, which allows you to specify a starting value for the sum. By default, start is set to 0.

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

Output:

25

In this example, you pass both the list of numbers and a starting value of 10 to the sum() function. The function starts the sum at 10 and adds the numbers in the list to it, resulting in a total of 25.

Summing Numeric Values

Now that you know how to use the sum() function, let’s look at some examples of summing numeric values. Python’s sum() function is quite versatile and can handle a variety of numerical data types, including integers, floating-point numbers, and even complex numbers.

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

Output:

15

In this example, you pass a list of integers to the sum() function and it returns the sum of all the integers.

numbers = [1.5, 2.5, 3.5, 4.5, 5.5]
total = sum(numbers)
print(total)

Output:

17.5

In this example, you pass a list of floating-point numbers to the sum() function and it returns the sum of all the floating-point numbers.

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

Output:

(15+20j)

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

Concatenating Sequences

In addition to summing numbers, Python’s sum() function can also concatenate sequences, such as lists and tuples. This is especially useful when you need to flatten a list of lists or combine multiple sequences into one.

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

Output:

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

In this example, you pass a list of lists to the sum() function, along with an empty list as the starting value. The function concatenates all the sublists together, resulting in a flat list.

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

Output:

(1, 2, 3, 4, 5, 6, 7, 8, 9)

In this example, you pass a list of lists to the sum() function, along with an empty tuple as the starting value. The function concatenates all the sublists together, resulting in a concatenated tuple.

Practicing With Python’s sum()

Now that you’re familiar with the basics of Python’s sum() function, let’s practice using it with some examples.

Computing Cumulative Sums

One common use case of the sum() function is to compute the cumulative sum of a list of numbers. The cumulative sum is the sum of all the numbers up to a given position.

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

Output:

[1, 3, 6, 10, 15]

In this example, you use a list comprehension to iterate over each position in the numbers list. For each position, you slice the list up to that position and pass it to the sum() function. This gives you the cumulative sum up to that position.

Calculating the Mean of a Sample

Another common use case of the sum() function is to calculate the mean (average) of a sample. The mean is the sum of all the numbers divided by the total number of numbers.

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

Output:

3.0

In this example, you calculate the sum of the numbers list using the sum() function, and then divide it by the length of the list to get the mean.

Finding the Dot Product of Two Sequences

The sum() function can also be used to calculate the dot product of two sequences. The dot product is a mathematical operation that takes two equal-length sequences and returns a single value.

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

Output:

32

In this example, you use a generator expression inside the sum() function to iterate over the elements of both sequences simultaneously. You multiply the corresponding elements together and sum up the results to get the dot product.

Flattening a List of Lists

As mentioned earlier, you can use the sum() function to concatenate lists and flatten a list of lists.

nested_lists = [[1, 2], [3, 4], [5, 6]]
flat_list = sum(nested_lists, [])
print(flat_list)

Output:

[1, 2, 3, 4, 5, 6]

In this example, you pass a list of lists to the sum() function, along with an empty list as the starting value. The function concatenates all the sublists together, resulting in a flat list.

Using Alternatives to sum()

While Python’s sum() function is a powerful tool for summation, there are cases where alternative functions and tools may be more appropriate or efficient.

Summing Floating-Point Numbers: math.fsum()

When working with floating-point numbers, the sum() function may introduce small rounding errors due to the way floating-point arithmetic works. In such cases, you can use the math.fsum() function from the math module, which provides a more accurate summation algorithm for floating-point numbers.

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

Output:

0.5

In this example, you import the math module and then use the math.fsum() function to sum a list of floating-point numbers. The result is a more accurate sum without any rounding errors.

Concatenating Iterables With itertools.chain()

If you need to concatenate multiple iterables together, not just lists or tuples, you can use the itertools.chain() function from the itertools module. This function takes multiple iterables as arguments and returns a single iterable that combines them all.

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

Output:

[1, 2, 3, 4, 5, 6, 'a', 'b', 'c']

In this example, you import the itertools module and then use the itertools.chain() function to concatenate three different types of iterables together: a list, a tuple, and a string. The result is a single iterable that combines all the elements.

Concatenating Strings With str.join()

If you need to concatenate a sequence of strings together, you can use the str.join() method. This method takes an iterable of strings as an argument and returns a single string that combines them all.

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

Output:

Hello World

In this example, you use the str.join() method to concatenate a list of words together with a space as the separator. The result is a single string with all the words combined.

Conclusion

Python’s sum() function is a powerful and Pythonic way to sum a list of numeric values or concatenate sequences. It provides an efficient and concise solution to common summation problems in your code.

By understanding how to use the sum() function and its optional arguments, you can efficiently sum numeric values, concatenate sequences, and solve various summation problems in your Python programs.

Remember to consider alternative functions and tools when needed, such as math.fsum() for more accurate summation of floating-point numbers, itertools.chain() for concatenating multiple iterables, and str.join() for concatenating strings.

With the knowledge gained from this tutorial, you’ll be able to approach summation problems in your code more efficiently and effectively, making your Python programs cleaner and more readable. Happy coding!