First page Back Continue Last page Overview Graphics

Inserting Elements in Lists

Inserting items at arbitrary positions:

L.insert(index,item)

We like to buy cheese as well. Let's add it to our shopping list. For practical reasons it has to be positioned between “butter” and “bread”:

>>> shopping_list

['milk', 'egg', 'butter', 'bread', 'bananas']

>>> shopping_list.insert(3,"cheese")

>>> shopping_list

['milk', 'egg', 'butter', 'cheese', 'bread', 'bananas']

We could have done it like this as well:

>>> shopping_list = shopping_list[:3] + ["cheese"] + shopping_list[3:]

Attention: The previous way is inefficient, because a new list will be created!