Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading