You already know how to append elements at the end of a list. This is what you use the append method for. In this video you’ll learn how to insert elements at arbitrary positions in a list.
Here’s the video version of this article:
If you want to add elements at arbitrary indices, you can use the method insert(index, x), which inserts x at index:
>>> dates = [1994, 2001, 2005, 2014]
>>> dates.insert(2, 2003) # inserts 2003 at index 2
>>> dates
[1994, 2001, 2003, 2005, 2014]
You can insert an element at the end, which is what you also achieve using the append function. You can do it like so:
>>> dates.insert(len(dates), 2016)
>>> dates
[1994, 2001, 2003, 2005, 2014, 2016]
or you can use the new index the object will be at:
>>> dates.insert(6, 2018)
>>> dates
[1994, 2001, 2003, 2005, 2014, 2016, 2018]
You can even use any index greater than the last one:
>>> dates.insert(50, 2019)
>>> dates
[1994, 2001, 2003, 2005, 2014, 2016, 2018, 2019]
The index will be set to the next available index anyway. So, even though we tried to insert the new element at index 50, it will be at index 7 in this case:
>>> dates.index(2019)
7