+4

# Python list

why does this happen when using extend() and then insert()? a = [1, 2, 3, 4, 5] print(a) # Output ==> [1, 2, 3, 4, 5] a.extend([44]) print(a) # Output ==> [1, 2, 3, 4, 5, 44] a.insert(-1, len(a)) print(a) # Output ==> [1, 2, 3, 4, 5, 6, 44] If you notice, the extended number (44) goes to the end even if I have extended it before inserting the length of my list; len(a) == 6. Why is that happening?

7/7/2019 8:20:46 AM

Dolan Hêriş

+9

using insert with lists does always have the same behaviour: a = [0, 1, 2, 3, 4] # now insert “99” at index 2: a. insert(2, 99) # result is: [0, 1, 99, 2, 3, 4] # now insert “33” at index -1: a.insert(-1, 33) # result is: [0, 1, 99, 2, 3, 33, 4] So insert at index 2 is correct. insert creates a new empty element at index 2 and then fill it with the defined value. All the other elements will be shifted to the tight. The same will happen if your index is -1 which means the last position in your list. at this place it creates a new emty element, and therefor the original element will be shifted to the right.

+5

a short and final remark: if index given for insert is >= len(list) the element will be inserted at the real end of the list. As there is no index error if “out of index” value of 99 as index for a list with len = 5 causes no problem.

+4

if you will later have 789 as a real existing index it will work as explained in my sample - so something inserted there will appear as the second last position in the list.

+4

a.insert(-1, len(a)) print(a) # python takes list a[1,2,3,4,5,44], your argument len(a) (that equal 6 on that moment) and pastes it on choosing you position (before "-1" element). Output [1, 2, 3, 4, 5, 6, 44]

+2

This seems to work too: a.insert(len(a), len(a))

+2

I tried it. That’s true. and why is it like that!!!? a = [1,2,3,4] a.insert(789,55) #Output ==> [1,2,3,4,55] what if later we had a real index with this index number(789)?

+1

Use append to achieve the behavior you want. https://stackoverflow.com/questions/40954521/why-does-list-insert-1-not-work-in-python

+1

Thanks Drax . It is clear that I can use append(). but just wanted to make sure if is it because I didn’t save the extend() result into a variable that this is happening or what!? thanks anyway for your answer

+1

You don't need to save the result of extend because it modify the original list ;)

+1

thanks Lothar it is quite obvious and clear. thanks for your description.

+1

quite interesting :-)

+1

I don't understand how it will be shifted when insert function applied?

0

so why the insert() result will come before the extend() one! the extend() numbers should come before the insert() ones!

0

thanks Paul Jacobs your offer works perfectly even there are much more ways to solve the problem. Just wanted to know the answer of the question actually! why is it like that!?

0