Sling Academy
Home/Python/Python: 4 Ways to Find the Sum of a Numeric List

Python: 4 Ways to Find the Sum of a Numeric List

Last updated: June 11, 2023

This pithy, example-based article will walk you through a couple of different ways to calculate the sum of a numeric list (a list that contains only numbers) in Python. We’ll also discuss the performance of each approach so you can know how fast and efficient it is.

Using the sum() function

I think this is the go-to approach for most cases. It is concise, readable, and efficient. What you need to do is just call the built-in sum() function on your list and assign the result to a variable. Note that if your list is empty or contains non-numeric elements, a TypeError will be raised.

Example:

numbers = [1, 1.5, 2, 2.4, 3, 3.5, 4, 4.5, 5, 5.5]
result = sum(numbers)
print(result)

Output:

32.4

More about performance: The sum() function has a time complexity of O(n), where n is the length of the list. It has a space complexity of O(1), as it does not create any new data structures.

Using a for loop

This is a more verbose, manual, and iterative way to find the sum of a numeric list in Python. It is less readable and Pythonic than the preceding one. However, it gives more control over the logic and error handling. It can be customized to handle different types of elements or conditions in the list.

Example:

numbers = [1, 1.5, 2, 2.4, 3, 3.5, 4, 4.5, 5, 5.5]

result = 0

for number in numbers:
    if(type(number) == int or type(number) == float):
        result += number

print(result)

Output:

32.4

The performance of this method is similar to the built-in sum() function. The for loop has a time complexity of O(n), where n is the length of the list. It has a space complexity of O(1), as it only uses one extra variable to store the sum.

Using the reduce() function

You can use the reduce() function to apply a function to each pair of elements in the list and reduce them to a single value. In the context of this article, that single value is the sum we want to find. Note that you need to import the functools module before calling the reduce() function.

Example:

# Import the functools module
import functools

# Define a custom function that takes two arguments and returns their sum
def add(x, y):
    return x + y

numbers = [1, 1.5, 2, 2.4, 3, 3.5, 4, 4.5, 5, 5.5]
total = functools.reduce(add, numbers)

# Print the sum
print(total)

Output:

32.4

Regarding performance, the reduce() function has a time complexity of O(n) and its space complexity is O(1). Therefore, it’s fast and efficient, almost like the two earlier solutions.

More solutions

There’re still more ways to achieve the goal. However, they are not very different from the ones I showed you above. hey may have slightly different syntax or performance, but the logic is nearly identical.

For example, you can use a while loop instead of a for loop like this:

numbers = [1, 1.5, 2, 2.4, 3, 3.5, 4, 4.5, 5, 5.5]

# Initialize an index variable to zero
i = 0

# get the length of the list
count = len(numbers)

# Initialize a variable to hold the total
total = 0

while i < count:
    total += numbers[i]
    i += 1

print(total)

Output:

32.4

Conclusion

We’ve walked through several ways to compute the total of all elements in a numeric list in Python. In general, the first approach is the best choice in terms of both code readability and performance. The others might be used less often, but they are worth knowing. This tutorial ends here. Happy coding & enjoy your day!

Next Article: Python: How to Calculate the Average of a Numeric List

Previous Article: Python: Find the Min and Max in a Numeric List (4 Ways)

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots