Python index slicing

时间:2016-11-12 05:42:59

标签: python-2.7

I am running the following code

my_list = [9, 8, 7]
for k in range (3):
    my_list.insert(-k, k+1)
print(my_list)

output

[1,9,8,3,2,7]

but my output is

[1,9,8,7,3,2]

How 7 is coming at the end?

2 个答案:

答案 0 :(得分:1)

this is how the list changed with the three times insert

1,9,8,7

1,9,8,2,7

1,9,8,3,2,7

答案 1 :(得分:0)

Because list.insert (index, value) inserts value before the value at index. And since an index of -1 point to the last element of the list. So all your inserts (with an negative) index will insert before the last element.