How can I add an item to the beginning of a list?


#1

Question

How can I add an item to the beginning of a list?

Answer

We learned about a function called insert() that accepts 2 arguments: the position to insert at and the value to insert. If we had a list called my_list that contained the list [1, 2, 3, 4] and we used my_list.insert(0, 5), the resulting list would be [5, 1, 2, 3, 4]. This is because the 0th index is the beginning of the list!


FAQ: Learn Python- Lists and Functions - Appending to a list