Aug-27-2021, 02:35 PM
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.
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]