It will make Theta(n) next calls on the iterator, and Theta(n) additions, where n is the number of items you're summing.

That's as specific as you can be for the time complexity of an algorithm that calls unknown code. If the time taken for each addition depends on n (as for example it would when summing lists, like sum(list(range(i)) for i in range(n))), then that's going to affect the overall time complexity.

Answer from Steve Jessop on Stack Overflow
🌐
Reddit
reddit.com › r/learnprogramming › time complexity of summing an array of integers with infinite size
r/learnprogramming on Reddit: Time Complexity of summing an array of Integers with infinite size
August 27, 2024 -

I had an interview the other day and the interviewer stumped me with this question, was wondering if anyone could share some insight?

Context: summing a linked list is usually O(n) since you have to go through the list once. However, Python 3 integers are not fixed in size, and so can be any number of bytes long. How would this affect time complexity? I assumed any overhead from re-allocating memory would be O(1) and therefore not relevant to time complexity but the interviewer was clearly looking for another answer... Any help is appreciated!

Discussions

Python - Two Number Sum (time and space complexity) - Code Review Stack Exchange
I'm solving the classic problem of finding two numbers from an array that sum to a given value. Can anybody please check whether my analysis of time and space complexity is correct on this one? # O... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
May 14, 2022
arrays - time complexity ~~ python - Stack Overflow
Find the maximum subarray sum (Kadane's Problem) in an array containing negative numbers. Brute force is O(n²)/O(n³) — optimize to O(n). Find all pairs in an array that sum to a target value (retur... More on stackoverflow.com
🌐 stackoverflow.com
python - time complexity of summing algorithms - Stack Overflow
I've had a look through previous posts and I'm still struggling to find the T(n) and big O of these two recursive algorithms, each one takes a sequence of numbers as its argument and sums all numbe... More on stackoverflow.com
🌐 stackoverflow.com
Array sum speed
Try running your script on PyPy More on reddit.com
🌐 r/Python
13
5
February 14, 2014
🌐
DEV Community
dev.to › askyt › python-program-to-find-the-sum-of-an-array-bci
Python Program to Find the Sum of an Array - DEV Community
January 31, 2025 - Sum of the array is 45 · Time Complexity: O(n) Auxiliary Space: O(1) Python provides an inbuilt function sum() that directly computes the sum of an iterable. arr = [5, 8, 12, 20] print("Sum of the array is", sum(arr)) Sum of the array is 45 ...
🌐
Pythoncomplexity
pythoncomplexity.com › builtins › sum
Sum - Python Big-O: Time & Space Complexity
# sum() - O(n), clean, optimized numbers = list(range(10000)) total = sum(numbers) # Manual loop - O(n), same but more verbose total = 0 for num in numbers: total += num # Both have same complexity, sum() is preferred
🌐
Medium
medium.com › the-leetcode-grind › leetcode-02-running-sum-of-1d-array-eeabda8865eb
Leetcode #02: ‘Running Sum of 1D Array’ | by Shruti Mandaokar | The Leetcode Grind | Medium
March 18, 2023 - The space complexity of this solution is O(n), where n is the length of the input array nums. This is because we create a new array runningSum of the same length as nums to store the running sum values.
🌐
AlgoMonster
algo.monster › home › 1480. running sum of 1d array
1480. Running Sum of 1d Array - In-Depth Explanation
It starts with the first element ... need to traverse the array once, performing a single addition operation at each step, giving us O(n) time complexity with minimal code....
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › a-sum-array-puzzle
A Sum Array Puzzle - GeeksforGeeks
May 22, 2026 - Time Complexity: O(n) Auxiliary Space: O(n) The idea is to first calculate the total sum of all array elements. Then for every index, replace arr[i] with totalSum - arr[i], which gives the sum of all elements except the current element.
Find elsewhere
🌐
Quora
quora.com › What-is-the-time-complexity-of-calculating-sum-of-integers-in-an-array-both-1D-and-2D-using-recursion-and-how-can-you-improve-upon-that-time-complexity
What is the time complexity of calculating sum of integers in an array (both 1D and 2D) using recursion, and how can you improve upon that time complexity? - Quora
Answer (1 of 3): In general, recursion can always be replaced by an iterative solution + a queue. recursive solutions are sometimes easier to write, but I can't think of a case where the optimal recursive solution for a problem has a different time complexity than the optimal iterative solution. ...
🌐
AlgoCademy
algocademy.com › link
Time Complexity in Python | AlgoCademy
Time Complexity: O(n) because the loop runs n times. Space Complexity: O(1) because we are using a constant amount of extra space. ... An empty list: The function should return 0. A list with one element: The function should return that element. These cases are handled correctly by the sum_list ...
🌐
Finxter
blog.finxter.com › home › learn python blog › python sum() – a simple illustrated guide
Python sum() - A Simple Illustrated Guide - Be on the Right Side of Change
January 27, 2021 - The time complexity of the sum() function is linear in the number of elements in the iterable (list, tuple, set, etc.). The reason is that you need to go over all elements in the iterable and add them to a sum variable.
🌐
Stack Overflow
stackoverflow.com › questions › 79976302 › time-complexity-python
arrays - time complexity ~~ python - Stack Overflow
Find the maximum subarray sum (Kadane's Problem) in an array containing negative numbers. Brute force is O(n²)/O(n³) — optimize to O(n). Find all pairs in an array that sum to a target value (retur...
Top answer
1 of 3
2

You're summing a list of N numbers of any size, in any order.

You aren't going to find a clever way to do that faster without some constraints.

It's Ω(N) always (lower bound is N addition operations - you won't get any better than that).

As a commenter below noted your algorithm may in fact be worse - it just can't be better.

2 of 3
1

Edited: corrections made based on comments regarding O(n) performance of [::].

TL;DR: It could be O(n), but your version is O(n²).

Remember that all of the big-O notations assume "times a constant". That is, O(n) really means O(k * n), and O(log n) really means O(k * log n).

Let's look at your first example:

def sum(numberSequence):
    assert (len(numberSequence) > 0)
    if (len(numberSequence) == 1):
        return numberSequence[0]
    else:
        return sum(numberSequence[-1]) + numberSequence[:-1]

The first line is assert plus compare plus len. The len operation is a constant time for lists and tuples (But it might not be with some other data structure! Beware!), compare is a constant time, and the assert is effectively a constant time, because if it ever fails the whole thing blows up and we stop computing. So let's just call assert a function call plus a comparison plus a return.

Now, how many times does this function get called? Well, the termination condition obviously represents one time, and every other time it's recursing on a list that is one shorter than the previous list. So the function will be called len(numberSequence) times, which is n for our purposes.

So we have

  1 * call (for the user calling us)
+ n * assert 
+ n * len 
+ n * compare

Next, we have the if statement that marks the termination condition for your recursion. Obviously, this statement will only be successful once (it's the termination condition, right? Only happens at the end...) so that's a comparison each time, and once per sum it's a return of a constant index.

  n * compare
+ 1 * constant index
+ 1 * return

Finally, there is the else: branch. I'm pretty sure you have a bug, and it should really be this (note position of colon):

        return sum(numberSequence[:-1]) + numberSequence[-1]

In that case you return the sum of a constant negative index lookup and a recursive function call of a slice. You only do this when it's NOT the end of the recursion, so n-1 times.

  (n - 1) * constant negative index lookup
+ (n - 1) * slice
+ (n - 1) * recursive call
+ (n - 1) * return

But wait! If you look around for people asking about how to make a copy of a list, you'll find that one common Python idiom is copy = orig[:]. The reason for this is that a slice operation makes a copy of the subrange of the list it is slicing. So when you say numberSequence[:-1] what you're really saying is copy = [orig[i] for i in range(0, len(orig)-1)].

This means that the slice operation is O(n), but on the plus side it's written in C. So the constant is a much smaller one.

Let's add those up:

  1 * call
+ n * assert 
+ n * len
+ n * compare
+ n * compare
+ 1 * constant index 
+ 1 * return
+ (n - 1) * constant negative index lookup
+ (n - 1) * (c * n) slice
+ (n - 1) * recursive call
+ (n - 1) * return

If we assume that constant index and constant negative index take the same time, we can merge them. We can obviously merge the returns and the calls. Which leaves us with:

   n * call
 + n * assert 
 + n * len
 + n * compare
 + n * compare
 + n * constant (maybe negative) index 
 + n * return
 + (n - 1) * (c * n) slice

Now according to "the rules," this is O(n²). Which means that all the details of O(n) behavior fall by the wayside in favor of that big, fat O(n²).

However:

If the len operation were not O(1) - that is, constant time - then the function might well become O(n²) because of that.

If the index operations were not O(1), because of underlying implementation details, the function might become O(n²) or O(n log n) because of that.

So you have implemented an algorithm that could be O(n) using a Python operator that is inherently O(n) itself. Your implementation is "inherently" O(n²). But it can be fixed. Even if fixed, things outside of your control could make your code slower. (But, that's outside your control, so ... ignore it!)

How can we fix your code to make it O(n)? By getting rid of the slice! You don't need that anyway, right? You just need to track the range.

def sum(numberSequence, start=0, end=None):
    assert (len(numberSequence) > 0)
    if end is None:
        end = len(numberSequence) - 1
    if end == start:
        return numberSequence[start]
    else:
        return sum(numberSequence, start, end-1) + numberSequence[end]

In this code, I'm doing pretty much the same thing that you did, with two differences. First, I've added a special case to handle being called by an end user with only the sequence as an argument. And second, of course, there is no slice. With that out of the way, the code is no longer inherently O(n²).

You can do the same math, and make the same changes, to your other example, but it's more complex. However, I will remind you that the sum of 2i for i = 0..n-1 is 2n - 1. As @lollercoaster points out, there ain't no such thing as a free lunch: you have to add up all the numbers.

🌐
Readthedocs
oi.readthedocs.io › en › latest › language › python › time_complexity.html
Time complexity — Organize everything I know documentation
Python » · Time complexity · Edit on GitHub · If you handle big data, it is faster to use sys.stdin.readline but I don’t know why sys.stdin.readline is fater than input.
🌐
Reddit
reddit.com › r/python › array sum speed
r/Python on Reddit: Array sum speed
February 14, 2014 -

I'm working on optimizing a python implementation of the Structural SIMilarity (SSIM) index by Zhou Wang, Alan C. Bovik, Hamid R. Sheikh and Eero P. Simoncelli (link). I'm not sure I can actually do anything at this point, but it's worth a shot because who doesn't want things to run faster if possible?

Essentially my problem boils down to the post title, how quickly I can sum arrays. I'm using a somewhat modified version of the algorithm which appears to give solid results, though I don't really get much of the math/methodology. The key difference between the original and the version I'm using is that this modified version divides both images into chunks and performs similarity analysis on each chunk, averaging the result over the size of the full image at the end.

After some experimentation I arrived at the conclusion that the fastest array sum function is numpy's einsum function. I don't know if a faster function exists, but I haven't found it yet if it does.

In order to do the actual image analysis, I give the main analysis function each image and then create a set of nested for loops, using the iterator from each for loop to slice the image arrays along the x and y axis and then pass the chunks to the function which actually calculates the similarity index. Since I do 3 summations per chunk, this means that the total number of summations is: ((imagesize/chunksize)2 ) x 3 x numimages

I'm wondering if there's anything I can do to speed things up, either in regards to how I'm summing the matrices or my approach to processing the chunks.

TL;DR gotta go fast

🌐
Python Pool
pythonpool.com › home › tutorials › python sum(): start values, generators, and common mistakes
Python sum(): Start Values, Generators, and Common Mistakes
July 13, 2026 - For more complex transformations, move the logic into a named helper so the expression remains easy to read. A generator expression also keeps memory use low because values are produced one at a time. This matters when summing values from large files, database rows, or streamed records. The start argument sets the initial total and supports a deliberate identity value. Booleans are integers in Python...
🌐
Reddit
reddit.com › r/learnprogramming › can we fins the sum of array elements in o(log(n)) if so how?
Can we fins the sum of array elements in O(log(n)) if so how? : r/learnprogramming
February 4, 2023 - no, u cant find the sum in o(log n) , as u have to iterate over every element to find the sum of an array. u can refer to a gfg article on how to find the sum in the most efficient way. 2,000 free sign ups for the Automate The Boring Stuff With Python course on Udemy (Jan 2026)