Lists and for loops

Hi everyone .Here is again a python list problem I am stuck on this once again :slight_smile:

my_list = [1, 2]

for v in range(2):
    my_list.insert(-1 , my_list[v])

print(my_list)

Now I though the answer would be [1,1,2,2,]
But NO!
the answer is [1,1,1,2]
Can someone pls explain how?

1 Like

The answer to your question is actually on StackOverflow: python - Array: Insert with negative index - Stack Overflow

Basically insert at -1 inserts the item before the position specified (so before the last element). Also remember the list is being mutated as you go.

So the first iteration of the loop results in: [1, 1, 2] because the element at index 0 is 1 and we insert it before the last element. The second iteration results in [1, 1, 1, 2] because the new value at index 1 is now 1 and we insert it before the last element.

1 Like