Introduction
List basics
9. Deleting elements by index
Lists with if statements and loops
Lists in functions
Summary

Instruction

Good. If you want to delete an element from a list, there are a few ways to do so. Use the del operator if you know the index.

# define a list
companies = ['Royal Dutch Shell', 'BP', 'Total', 'Volkswagen', 'Glencore Xstrata', 'Gazprom']

# delete Total
del companies[2]

When you delete companies[2], the next element (companies[3], which is Volkswagen) takes its place, and all elements with higher indices are shifted so that there are no empty spaces in your list. This is an important concept: deleting an item can change multiple indices in your list.

Del image

Exercise

Get rid of the very first element in the water_level list.

Stuck? Here's a hint!

The first element has an index of 0.