I learned from this answer that the fastest method to insert an item at an index would be like this:
a = [1, 2, 3, 4, 5]
a[2:2] = ["12345"]
But I don't know why. And I learned from this answer that the complexity would never be O(1).
I tried the following and verified the statement that it should be larger than O(1).
python3 -m timeit --setup="a = list(range(1000))" "a[500:500] = [3]"
50000 loops, best of 5: 3.89 usec per loop
python3 -m timeit --setup="a = list(range(100000))" "a[500:500] = [3]"
10000 loops, best of 5: 20.1 usec per loop
python3 -m timeit --setup="a = list(range(1000000))" "a[500:500] = [3]"
1000 loops, best of 5: 340 usec per loop
I thought that we can pinpoint the address/pointer in O(1) and then we only need to direct that address to the new item, and it would be O(1). I thought I should be wrong since that would scoot over the addresses of the items on the right side.
I tried to see what is a[2:2]
but it turns out to be just an empty list. I thought it would be possible to separate the indexing and the assignment. I mean if we can first get the pointer of a particular index and then make it point to a new item?
In [14]: a = [1, 2, 3, 4, 5]
In [15]: b = a[2:2]
In [16]: b = ["12345"]
In [17]: b
Out[17]: ['12345']
In [18]: a
Out[18]: [1, 2, 3, 4, 5]
In [19]: a[2:2] = ["12345"]
In [20]: a
Out[20]: [1, 2, '12345', 3, 4, 5]
In the code above I want to get the pointer by b=a[2:2]
and then redirect that to a new item "12345"
by b = ["12345"]
.
What's going on under the hood? Any suggestions would be very appreciated. Thanks in advance.