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!

I don't understand time complexity. Nov 29, 2020
r/learnprogramming
5y ago
How to Figure out the Time Complexity of my code? Jun 7, 2022
r/learnprogramming
4y ago
Are time complexities important? Nov 15, 2024
r/learnprogramming
last yr.
How to sum an array together in python? Apr 9, 2019
r/learnpython
7y ago
1. Two Sum (time complexity) Oct 27, 2024
r/leetcode
last yr.
More results from reddit.com
Discussions

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
algorithms - Can we find the sum of a sorted array in O(logn) time? - Mathematics Stack Exchange
So, I know the time Complexity ... the sum using $O(\log n)$ time complexity? I believe we can do it using a Binary search method. I might be wrong, but can we actually do it in $O(\log n)$ time complexity? ... David G. Stork · 30.7k55 gold badges3434 silver badges6262 bronze badges ... $\begingroup$ Are all the elements of your array necessarily contiguous ? Like in your example ... More on math.stackexchange.com
🌐 math.stackexchange.com
May 14, 2022
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
🌐
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 - # Function to calculate sum using a loop def sum_array(arr): total = 0 for num in arr: total += num return total # Example usage arr = [5, 8, 12, 20] print("Sum of the array is", sum_array(arr)) Sum of the array is 45 · Time Complexity: O(n) ...
🌐
Pythoncomplexity
pythoncomplexity.com › builtins › sum
Sum - Python Big-O: Time & Space Complexity
# O(n*k) where k = time for __add__ class Vector: def __init__(self, *components): self.components = components def __add__(self, other): # O(m) where m = number of components return Vector(*(a + b for a, b in zip(self.components, other.components))) def __repr__(self): return f"Vector{self.components}" vectors = [Vector(1, 2), Vector(3, 4), Vector(5, 6)] result = sum(vectors, Vector(0, 0)) # Vector(9, 12) # Complexity: O(n*m) where n=3 vectors, m=2 components
🌐
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. ...
🌐
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 - Code: Let’s check out a practical ... function in Python. The time complexity of the sum() function is linear in the number of elements in the iterable (list, tuple, set, etc.)....
🌐
Medium
medium.com › @AlexanderObregon › solving-the-two-sum-problem-on-leetcode-python-answer-s-walkthrough-f0c737fb3648
Solving the 'Two Sum Problem' on LeetCode — Python ...
April 13, 2024 - The outer loop runs ’n’ times, and for each iteration of the outer loop, the inner loop runs ‘n-i’ times, where ‘i’ is the current iteration of the outer loop. This behavior results in a time complexity of O(n²), as each element is compared with every other element in the array.
🌐
AlgoMonster
algo.monster › home › 1480. running sum of 1d array
1480. Running Sum of 1d Array - In-Depth Explanation
This pattern of maintaining a cumulative sum as we iterate through the array is exactly what Python's accumulate function does internally. It starts with the first element and keeps adding each subsequent element to the accumulated sum, yielding each intermediate result. The beauty of this approach is its efficiency - we only need to traverse the array once, performing a single addition operation at each step, giving us O(n) time complexity with minimal code.
Find elsewhere
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.

🌐
AlgoCademy
algocademy.com › link
Time Complexity in Python | AlgoCademy
Express the total time complexity using Big O notation. ... def sum_list(lst): # Initialize total to 0 total = 0 # Iterate through each number in the list for num in lst: # Add the number to the total total += num # Return the total sum return total
🌐
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, so True contributes 1 and False contributes 0.
🌐
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.
🌐
AlgoCademy
algocademy.com › link
Time Complexity Practice 1 in Python | AlgoCademy
# Example of len() function my_list = [1, 2, 3, 4, 5] print(len(my_list)) # Output: 5 # Example of sorted() function unsorted_list = [5, 3, 1, 4, 2] print(sorted(unsorted_list)) # Output: [1, 2, 3, 4, 5] # Example of sum() function numbers = [1, 2, 3, 4, 5] print(sum(numbers)) # Output: 15 # ...
🌐
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. In this post, we discussed an efficient solution to the Leetcode problem “Running Sum of 1d Array” using Python. We provided a clear and concise Python code solution, along with a detailed analysis of the time and space complexity.
🌐
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...
🌐
Medium
medium.com › @ashutosh0626 › time-complexity-in-python-simply-explained-88b496f29a56
Time Complexity in Python Simply Explained | by Ashutosh Sharma | Medium
April 13, 2023 - Therefore, one should perform a time complexity analysis on the worst-case input to get the most accurate results. import time def sum_list(lst): start = time.time() total = 0 for num in lst: total += num end = time.time() return total , ...