Home > other >  How come does the output add [1, 1, 1] instead of [1] here?
How come does the output add [1, 1, 1] instead of [1] here?

Time:09-05

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

The output is then:

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

I am completely lost as to how three 1s are added to my_list. Can someone explain?

CodePudding user response:

Insert(pos, val) inserts val as a new item to your list at position pos. Since len(my_list)=3 initially, the loop is executed 3 times:

  1. my_list[0]=1 is inserted to position 1, making my_list = [1, 1, 2, 3]

  2. my_list[1] = 1 is inserted to position 1 giving my_list = [1, 1, 1, 2, 3]

  3. Same as in step 1 and 2: my_list = [1, 1, 1, 1, 2, 3]

CodePudding user response:

You are inserting three times the value 1 at the position 0, 1 and 2. Therefore, the array is:

v = 0 -> [*1*, 1, 2, 3]
v = 1 -> [1, *1*, 1, 2, 3]
v = 2 -> [1, 1, *1*, 1, 2, 3]

Moreover, I don't understand how you can print v if that variable can only be used within the for.

  • Related