todd2323 todd2323 - 3 months ago 8
Python Question

why am I not getting a 4 in this list?

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


I am getting:
[1,9,8,3,2,7]

I have changed the insert and tested it with different numbers and do not understand. I thought -1 would insert at the end of the list.

Answer

The insert(i, x) function insert a new item with value x in the list before position i. my_list[-1] is the end element, so my_list.insert(-1, 2) will insert before the end element 7.

for k in range (3): my_list.insert(-k,k+1) 

my_list.insert(0,1) --> my_list = [1, 9, 8, 7]
my_list.insert(-1,2) --> my_list = [1, 9, 8, 2, 7]
my_list.insert(-2,3) --> my_list = [1, 9, 8, 3, 2, 7]
Comments