How to compute the sum of a list in python

Key takeaways:

  • Python provides various ways to compute the sum of a list, including simple loops, recursion, and the built-in sum() function. Each method has its use case and complexity.

  • The sum() function is the simplest and most efficient way to calculate the sum, especially for straightforward use cases.

  • Exploring approaches like loops and recursion can help you understand fundamental Python concepts such as iteration and function calls.

Calculating the sum of a list is a common task in Python—useful in data analysis, algorithms, and more. Python provides multiple ways to achieve this, from simple built-in functions to custom methods using loops or recursion. This Answer explores all these approaches.

A high-level diagram of the sum function
A high-level diagram of the sum function

Calculating the sum of a list

Here are the techniques to compute the sum of a list in Python:

1. Using a simple loop

The most basic solution is to traverse the list using a for/while loop, adding each value to the variable, total. This variable ​will hold the list sum at the end of the loop. Here’s an example code:

def sum_of_list(l):
total = 0
for val in l:
total = total + val
return total
my_list = [1,3,5,2,4]
print("The sum of my_list is", sum_of_list(my_list))

2. Computing the sum recursively

Instead of using loops, we will calculate the sum recursively. Once the end of the list is reached, the function will roll back. The sum_of_list function takes two arguments as parameters: the list and the index of the list (n). Initially, n is set at the maximum possible index in the list and decremented at each recursive call. Here’s an example code:

def sum_of_list(l,n):
if n == 0:
return l[n];
return l[n] + sum_of_list(l,n-1)
my_list = [1,3,5,2,4]
print("The sum of my_list is", sum_of_list(my_list,len(my_list)-1))

3. Using the sum() method

This is the simplest approach. Python has a built-in sum() function to compute the sum of the list. Here’s an example code:

my_list = [1,3,5,2,4]
print("The sum of my_list is", sum(my_list))

Learn the basics with our engaging Learn Python course!

Start your coding journey with Learn Python, the perfect course for beginners! Whether exploring coding as a hobby or building a foundation for a tech career, this course is your gateway to mastering Python—the most beginner-friendly and in-demand programming language. With simple explanations, interactive exercises, and real-world examples, you’ll confidently write your first programs and understand Python essentials. Our step-by-step approach ensures you grasp core concepts while having fun. Join now and start your Python journey today—no prior experience is required!

Conclusion

Python offers various ways to sum a list, with the sum() function being the simplest and most efficient. Exploring alternative methods like loops and recursion can enhance your understanding of Python and iteration concepts.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is += in Python?

  • += is the addition assignment operator.
  • It assigns the result back to the variable after adding the value on the right to the variable on the left.

What is *= in Python?

  • *= is the multiplication assignment operator.
  • It assigns the result back to the variable on the left after multiplying it by the value on the right.

What is the sum() function in Python?

The sum() function in Python is used to calculate the sum of all the elements in an iterable (like a list, tuple, or set). It adds up the numeric values in the iterable and returns the total. By default, it starts the sum at 0, but you can specify a different starting value if needed.


Can I use the sum() function for non-numeric elements in Python?

The sum() function in Python is primarily designed to work with numeric elements (e.g., integers or floats). If you attempt to use it on non-numeric elements, it may result in a TypeError.


Can I sum elements in a nested list in Python?

The sum() function in Python cannot directly sum elements of a nested list (a list within a list), as it only works with flat iterables. However, you can flatten the list first or use a more advanced approach like a list comprehension or recursion.



Here are a few ways to sum elements in a nested list:

  1. Using a list comprehension (flat sum):
from functools import reduce
import itertools

def flatten(lst):
    """Recursively flatten a nested list."""
    if not lst:
        return []
    if isinstance(lst[0], list):
        return flatten(lst[0]) + flatten(lst[1:])
    return [lst[0]] + flatten(lst[1:])

def sum_nested_list(nested_list):
    """Sum all elements of a nested list using reduce and map."""
    return reduce(lambda x, y: x + y, map(int, flatten(nested_list)))

# Creating a deeply nested list for added complexity
nested_list = [[1, [2, 3]], [[4], 5], [[[6]]]]

# Compute the sum
total = sum_nested_list(nested_list)

print(total)  # Output: 21

  1. Using recursion (if you have deeper nesting levels):
from collections.abc import Iterable

def deep_flatten(lst):
    """Generator function to recursively flatten a deeply nested iterable."""
    for item in lst:
        if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
            yield from deep_flatten(item)  # Recursively yield elements
        else:
            yield item

def flatten_and_sum(lst):
    """Flattens a deeply nested list and sums its elements."""
    if not isinstance(lst, (list, tuple, set)):
        raise TypeError("Input must be a list, tuple, or set.")
    
    return sum(deep_flatten(lst))

# Complex deeply nested structure
nested_list = [[1, 2, [3, [4, 5]]], {6, 7, (8, 9)}, [[10], [11, {12, 13}]]]

# Compute the sum
total = flatten_and_sum(nested_list)

print(total)  # Output: 91

These approaches allow you to sum all elements in a nested list, regardless of how deep the nesting is.


What happens if my list is empty in Python?

If you pass an empty list to the sum() function, it will return the starting value (which defaults to 0 for numeric types). In other words, the sum of an empty list is 0.


How to sum multiple lists in Python?

To sum multiple lists in Python, you can use the sum() function along with unpacking, or you can concatenate the lists and then sum the elements. Here are a few approaches:

1. Using sum() with unpacking:

You can use the * operator to unpack multiple lists and pass them as arguments to the sum() function.

Unpacking refers to extracting individual elements from an iterable (like a list, tuple, or dictionary) and assigning them to variables.

Example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

result = sum([*list1, *list2, *list3])
print(result)  # Output: 45

2. Using sum() with lists inside a list:

You can pass a list of lists to the sum() function and add them by using the + in relation to the sum() function.

Example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

result = sum(list1 + list2 + list3)
print(result)  # Output: 45

3. Using a loop to sum lists element-wise:

If you want to add corresponding elements of multiple lists (i.e., perform element-wise addition), you can use zip() along with a loop.

Example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

result = [sum(x) for x in zip(list1, list2, list3)]
print(result)  # Output: [12, 15, 18]

This approach sums the corresponding elements from each list.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved