List manipulation: how can I append to middle of the list?


I do understand how to append to the tail of the list using .append(). But how do I add an item in the middle of list, let's say I want to add newly_added in the place of my_list[2] and consequently every related items step backward? Thanks.

Replace this line with your code.


hi @can0r,

I believe this was mentioned in 9. Python lists and dictionaries. :slight_smile:

To do so, you can simply use the list_name.insert(index, newly_added) function.

For example, you start out with a list animals = ["ant", "bat", "bird"] and you want to insert "dog" right behind "ant". To do so, you just have to do animals.insert(1, "dog"), and if you print the list again afterwards, you will realise that "dog" has been added in right where you want while "bat" and "bird" have shifted back by one index correspondingly. (Remember that you start counting indexes from 0!)

Hope this helps :slight_smile:


How stupid of me forgot .insert.
Thank you for enlightening me :slight_smile: