CPython list.insert(index) real time complexity, when all inserts occur at same index?

Question:

My noob question is in the title

I have some code that iteratively builds a list. All inserts are always at the second-to-last position. Is list.insert(-1, value) truly an O(1) operation in the CPython implementation?

O(?) -> what I want to do

some_list = ['always first', 'always last']
for i in range(10000):
    some_list.insert(-1, 'value')

O(1) -> above code is functionally equivalent to this

some_list = ['always first', 'always last']
for i in range(10000):
    last = some_list.pop()
    some_list.append('val')
    some_list.append(last)

In list.insert(-1, val) does CPython always re-build the index from the very first position, no matter the insert index?

Or are these two code snippets the same time complexity in their CPython implementation?

Asked By: scotty-nukem

||

Answers:

Why don’t you just write:

last = some_list.pop()
for i in range(10000):
    some_list.append(value)
some_list.append(last)

and you’re guaranteed O(1) and more efficient code.

But I suspect your first example is also O(1) since only one element has to be moved every time. It just won’t be as efficient as the code above.

Have you considered writing two examples, one with range(500000) and the second with range(1000000)? This will quickly let you know if the algorithm is O(1) or quadratic.

Answered By: Frank Yellin