Python Forum

Full Version: myList.insert(index, element) question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Why does the "insert.(index, element)" function work backwards in this for loop when used in the context "myList.insert(1, myList[v])"? Instead of adding 0, 1, and 2 to the list to the "myList[1]" location during iteration it will instead add 1 to myList[0], myList[1], and myList[2] during iteration.

Used outside of the loop "myList.insert(4, 8)" it will behave as expected adding 8 to "myList[4]" location.

myList = [1,2,3]
print("This is my initial list: ", myList)
for v in range(len(myList)):
    print("This is v: ", v)
    myList.insert(1, myList[v])
    print("This is my list during iteration: ", myList)
print(myList)

myList.insert(4, 8)
print(myList)
I couldn't upload an image of my output, but here is a copy/paste view of my output.

Output:
This is my initial list: [1, 2, 3] This is v: 0 This is my list during iteration: [1, 1, 2, 3] This is v: 1 This is my list during iteration: [1, 1, 1, 2, 3] This is v: 2 This is my list during iteration: [1, 1, 1, 1, 2, 3] [1, 1, 1, 1, 2, 3] [1, 1, 1, 1, 8, 2, 3]
What do you mean by "work backward"? The action is a bit confusing because you're modifying a list at the same time as you're reading it for information.

Start with [1, 2, 3].
First time through the loop, you tell it copy element 0 (which is a 1) to spot 1. -> [1, 1, 2, 3]
Next time through the loop, you tell it copy element 1 (which is now a 1) to spot 1 -> [1, 1, 1, 2, 3]
Next time through the loop, you tell it copy element 2 (which is now a 1) to spot 1 -> [1, 1, 1, 1, 2, 3]

It doesn't add 1, 2, 3 because myList has changed by the time the element is looked for.