Lists#

So far the variables we’ve worked with hold a single item of data (one integer, one string, etc.) called scalar variables. A list in Python is a variable that can hold any number of items. The values are held in order. Think of my to-do list:

  1. Eat

  2. Sleep

  3. Program

  4. Repeat

A list variable gives us the ability to hold all four values in a single variable. Think of it like this:

Image of todo_list

Notice that the first item in the list is index zero. In this lecture you’ll learn how to create, use and change (or mutate) lists.

Create a List Variable#

A list variable is a way to hold those data items together. Here’s an example where I define a list variable called todo_list that contains strings:

todo_list = ["Eat", "Sleep", "Program", "Repeat"]

Enter my todo_list into the next cell and print it:

[ ]:

A list can have any number of elements (millions and billions!). Here’s an extended todo list:

todo_list = ["Eat", "Sleep", "Eat Again", "Eat More", "Nap", "Program", "Repeat"]

A list can have no items too. Here’s an empty list:

todo_list = []

Lists are they’re own type in Python. Type this example into the next cell:

print(type(todo_list))
[ ]:

What type is the list?

Lists can also be created using by conversion. For example you can create an empty list like this:

todo_list = list()

The conversion syntax will be more important later. For now we’ll use square brackets [ and ].

Accessing List Elements#

A list variable gives you access to individual elements in the list. You can use elements just like any other with square brackets ([ and ]). When you use a list variable you have to choose, do you want to sue the whole list or just one element. For example:

print(todo_list)      # Print the whole list
print(todo_list[0])   # Print the firt element

Try both print statement in the next cell:

[ ]:

Lists indexes start at zero! Element [0] of the list is the first element. It takes a little getting used to but it makes many things easier to program when lists start at zero.

Important!

I will ask you questions about lists using precise language so that you know exactly what index to use. Here’s what I’ll say:

  • “Index n” means the exact index. For example:

    • “Print index three of todo_list,” means print(todo_list[3]).

  • “The n-th element of…” means that n is the index plus one. For example:

    • “Print the third element of todo_list,” means print(todo_list[2])

A single list element can be used just like any of the variables you’ve written so far, variables that conatin a single value. You can assign list elements too. When you do the list is changed. Here’s an example of you you change a list element:

todo_list = ["Eat", "Sleep", "Program", "Repeat"]
todo_list[0] = 'Wake up'
print(todo_list)

Enter the example into the next cell:

[ ]:

Try changing the element index. Do you see how the list changes?

Adding and Removing Elements#

Lists can have any number of elements. You can add elements using the append and insert functions and remove them with the remove function and del operator. Why are append, insert and remove functions and del an operator? The answer is a bit complicated, but in short append, insert and remove are specific to a list, del works on lists and other data types too so it’s more generic.

The append Function#

The append function adds an item to the end of the list. For example:

todo_list = [] # Start with an empty list.
todo_list.append('Eat')
todo_list.append('Sleep')
todo_list.append('Program')
todo_list.append('Repeat')
print(todo_list)

Type the code into the next cell.

[ ]:

Run the debugger to watch the list change!

The insert Function#

The insert function adds an element to the list in any place you like. Calling insert displaces existing elements which are moved to the next index. Think of it as them moving to the right. For example:

todo_list = ['Sleep', 'Repeat']
todo_list.insert(1, "Program") # Moves 'Repeat' over.
todo_list.insert(0, "Eat") # Puts this on the front, moving everything over.
print(todo_list)

Try entering in the statements:

[ ]:

Can you predict the order after running this code? Try running it in the debugger.

The del Operator#

The del operator deletes an element from the list by index*. It looks a little different than append and insert. The del operator removes an element at a particular index making a gap. Remaining elements to the right move left to fill the gap (the opposite of what insert does). Here’s an example of del:

todo_list = ['Eat', 'Sleep', 'Work', 'Repeat']
del todo_list[2] # No more Work!
print(todo_list)

Type in the example:

[ ]:

The remove Function#

The remove function removes an element from a list by value. You don’t need to know the index of the thing you want to remove. Other than that it’s jut like del, it moves the remaining elements over to the left. Here’s an example of remove:

todo_list = ['Eat', 'Sleep', 'Work', 'Repeat']
todo_list.remove('Work') # No more Work!
print(todo_list)

Try using the remove function in the next cell:

[ ]:

The clear Function#

You delete every item in a list using the clear() function.

todo_list = ['Eat', 'Sleep', 'Program', 'Repeat']
todo_list.clear() # All done!
print(todo_list)
[ ]:

Searching for Items With in#

You can ask Python to look for a particular value inside of a list with the in operator. The in operator returns True or False. For example:

todo_list = ['Eat', 'Sleep', 'Program', 'Repeat']
"Eat" in todo_list

Enter the example into the next cell:

[ ]:

What happens if you search for another string, like ``Laundry``?

You can modify in with not to get the opposite effect. Try that in the next cell:

[ ]:

It’s very common to use in with an if statement. For example:

todo_list = ['Eat', 'Sleep', 'Program', 'Repeat']
if 'Eat' in todo_list:
    print("Is it lunch time yet?")
else:
    print("Have you forgotten dinner?")

We’ll cover if statements in a future lesson.

List Length#

The len operator tells you the length of a list. You’ll use it a lot! For example:

todo_list = ['Eat', 'Sleep', 'Program', 'Repeat']
print("Things to do:", len(todo_list))

Try it yourself:

[ ]:

split and join: Converting Between Lists and Strings#

It’s very common to make a list from a string and vice-versa. For example, you have a sentence and you want to break it up into individual words. That’s done witht the split function. Here’s an example:

sentence = "Mary had a little lamb."
words = sentence.split()
print(words)

Try using split:

[ ]:

Notice the period ``.`` is still in there! The opposite of split is join. The join function takes a list and joins it together into a string. The join function is a little weird looking in Python becuase it operates on a separator. The separator is a character that is put in between the list items. Here’s the reverse of the split from the last example:

words = ["Mary", "had", "a", "little", "lamb."]
sentence = " ".join(words)
print(sentence)

Notice the " " that is used to join the list together. Try the example:

[ ]:

What happens when you change what’s in between the quotes?

List Errors#

When you access an element that’s beyond the end of the list you get an IndexError exception. Try this:

todo_list = ['Eat', 'Sleep', 'Program', 'Repeat']
print('The fifth item is:', todo_list[4])
[ ]:

Notice the error. Remember it! You’ll see it a lot!