Insert Method in Python

Hi. I am confused with the below code. Would greatly appreciate an explanation on how it resulted to the correct answer:

my_list = [1, 2, 3]
for v in range (len(my_list)):
    my_list.insert (1, my_list[v])
print (my_list)

[1, 1, 1, 1, 2, 3]

I understood it as → for each value in range (3) which is 0,1,2 → we will insert 0,1,2 to the index 1 position in the list. So for each time, I came up with the ff. new lists:
I inserted 0 to the index 1 position – > [1, 0, 2, 3]
Then I inserted 1 to the index 1 position → [1, 1, 0, 2, 3]
Then I inserted 2 to the index 1 position → [1, 2, 1, 0, 2, 3]
So my answer was [1, 2, 1, 0, 2, 3] which is wrong. Why?

Thanks!

You seem to expect your code to insert v into my_list but you are inserting my_list[v] instead. The value of my_list[v] is not v, it’s whatever that element of the list is.

I suggest you print out the value you are inserting right before you do it. Heck, print out the list, too! This is a very simple way to see what your code is doing step-by-step…it wouldn’t be feasible with a really long loop but it’s fine here.

my_list = [1, 2, 3]
for v in range (len(my_list)):
    # print out the value of my_list, v, and my_list[v]
    print(f"{my_list=}\t{v=}\t{my_list[v]=}")
    my_list.insert (1, my_list[v])
print (my_list)
1 Like

Ohhh… I get it now! Thank you for the explanation code.