Where you add an item to the end of a list with
append(). You can use
insert() to insert an item at the beginning of a list in Python.
The insert function takes two arguments. First the index of where the item should be inserted and second the actual item that should be inserted.
So the signature of the
insert() function is as follows:
You use the
insert() function actually to insert an item at any position, depending on the index you pass to it.
Since we want to add an item at the first position of the list we pass
0 as the first argument.
pizza_toppings = ['cheese', 'tuna'] pizza_toppings.insert(0, 'tomato sauce') print(pizza_toppings) # => ['tomato sauce', 'cheese', 'tuna']
The above example added
"tomato sauce" in the first position of the
pizza_topping list. Now the list makes sense.