Explain Codes LogoExplain Codes Logo

Sum a list of numbers in Python

python
functions
dataframe
pandas
Anton ShumikhinbyAnton Shumikhin·Mar 8, 2025
TLDR

Easily sum numbers in a list with sum() function:

total = sum([1, 2, 3]) # I can count to three with one hand behind my back, here's proof 👀 print(total) # 6. Yes, it's a 6, no surprises there!

Advanced operations

Let's dive deeper into the Pythonic ocean of summing numbers.

Dealing with decimals

Perfect precision, especially in financial calculations, matters! decimal.Decimal ensures that.

from decimal import Decimal # It's raining... it's pouring... financial accuracy is not boring! prices = [Decimal('4.20'), Decimal('2.50'), Decimal('1.99')] total = sum(prices) print(total) # Super-precise addition result.

Efficient summation with generators

For large data, use a generator. Keeps memory usage low.

numbers = range(1_000_000) # A truckload of numbers. # Count the grains of sand but remember... don't fall asleep. total = sum(n for n in numbers)

Pairwise averages

Sum adjacent pairs, get their average. Use zip() and slicing.

numbers = [10, 20, 30, 40, 50] # Adding these pairs up requires more braincells. Good thing Python has a big brain! pairwise_averages = [(x + y) / 2.0 for x, y in zip(numbers, numbers[1:])] print(pairwise_averages) # [15.0, 25.0, 35.0, 45.0]

Summing lists of varying lengths

sum() ain't scared of lists of unknown lengths, it handles them with ease:

# Three lists walk into a function... random_lengths = [sum([1, 2]), sum([10, 20, 30]), sum(range(4))] print(random_lengths) # [3, 60, 6]

Code refactoring for readability

Clear, simple code is easier to maintain. Keep it clean:

# Re-factor for clarity and simplicity. numbers_to_add = [1, 2, 3] total_sum = sum(numbers_to_add) # Purpose? Crystal. # We are keeping it clean, just like my room... hopefully!

Compatibility

Version matters. Ensure Python version compatibility for smooth sailing:

  • All examples are Python 3 compatible.
  • For Python 2, import division from __future__ for expected floating-point division.

Expert tips

Let's kick it up a notch with some tips:

Start the sum from a specific point

Specify a starting point, sum() can do that!

total = sum([1, 2, 3], 10) # Started from 10 now we here. print(total) # Yep, that's a 16!

Sum transformation with map

Transform elements and sum them, all in one:

# String numbers to integer transformation, all while summing! Legendary. numbers = ['1', '2', '3'] total = sum(map(int, numbers)) # Magic trick? Nah, just Python at its finest. print(total) # Output: 6