[Solved] Why does list.insert[-1] not work in python?


Say you have

some_list = [1, 2, 3]

and you do

some_list.insert(-1, 4)

You might think, “okay, -1 means the last index, so it’ll insert 4 at the last index”. But the last index is index 2, over here:

[1, 2, 3]
#      ^

It’ll insert 4 at that index, producing

[1, 2, 4, 3]
#      ^ 4 inserted here

You don’t want 4 to end up at the current last index. You want to insert 4 at index 3, an index that isn’t even in the list yet. You could do that with

some_list.insert(3, 4)

but it’s clearer to do

some_list.append(4)

1

solved Why does list.insert[-1] not work in python?