Previous Lesson Table of Contents Next Lesson

We make lists all the time: shopping lists, TODO lists, wish lists. Thus, it’s natural that Python would provide a list class for just that purpose. Lists can contain any Python objects that you choose as a comma-delimited sequence surrounded with brackets:

x = 1
l = [2, "cat", x]
print(l)

This will output:

[2, 'cat', 1]

We see here that our list contains a number, a string, and a variable! A very eclectic collection of Python objects if you ask me. :)

Python also supports multiple useful operations when it comes to handling lists, such as:

Adding Elements

You can add elements to a list by using the append method, which takes a single Python object to be added to the end of the list:

l = [1, 2, 3]
l.append("anything")
print(l)

This will output:

[1, 2, 3, 'anything']

Removing Elements

You can remove elements from a list by using the remove method, which takes any Python object to be removed from the list:

l = [1, 2, 3]
l.remove(2)
print(l)

This will output:

[1, 3]

What happens if we try to remove an element that already does not exist?

l = [1, 2, 3]
l.remove(4)

If we try to do this, Python will raise an error:

...
ValueError: list.remove(x): x not in list

Indexing

If we want to access the nth element in a list, we write out the list object (or the variable assigned to that list), followed by brackets containing the index corresponding to the element that we want:

l = [1, 2, 3]
print(l[1])

This will output:

2

That’s odd! Isn’t Python returning the 2nd element in the list? That’s because Python uses zero-indexing, meaning list indices begin at 0. Thus, the 2nd element of the list corresponds to an index of 1. More generally, the nth element of the list corresponds to an index of n - 1.

What happens if we try to access an index that does not exist?

l = [1, 2, 3]
print(l[1000])

If we try to do this, Python will raise an error:

...
IndexError: list index out of range

There are a lot of other list methods that are available beyond the ones listed, but we’ll stop here for the time being and practice what we have learned:

  • Create a list with the following elements: 23, "dog", and 5. (solution)

  • With your newly created list, append the element "cat" and remove the element 23 from your list. (solution)

  • With your modified list, how would you print the 1st element? (solution)

If you’re comfortable handling lists, feel free to proceed to Lesson 7!