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:

[ ]:

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.


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'

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.

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.

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!

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!

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!
[ ]:

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. 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?")
    print("Have you forgotten dinner?")

Try the code example, change in to not in to see what happens when you reverse the condition:

[ ]:

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:

[ ]:

Remebmer len()! It’s going to be essential in the next lecture.

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()

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)

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!

Lists as Function Arguments

You can pass a list to a function using an arument just like any other Python variable. When you pass a list to a function it’s said to be passed by reference. That means that there is only one copy of the list and if the function modifies it the list will be changed for the caller too. This behavior is different from the other variable types you’ve used so far.

Here’s an example that shows the difference:

def my_func(some_list, some_string):
    """Modify the string and the list"""
    some_list.append("Mike wuz here.")
    some_string += "--Mike"
    print("I changed things!")

my_list = [1, 2, 3, 4]
my_string = "A very proper string."
my_func(my_list, my_string)

print("My list:", my_list)
print("My string:", my_string)
I changed things!
My list: [1, 2, 3, 4, 'Mike wuz here.']
My string: A very proper string.

What does this example print? It might surprise you.

Notice how the string and list are different?

  • The function changes my_list and the change “sticks”.

  • The function changes my_string but the change is lost.

Note: Programming Style

Should you modify a list in a function? The answer is, “It depends.” In Python you have the flexability to decide how you want your program to work. There are often two ways of doing things. For example: You can sort a list

my_list.sort() # Sorts the list, changing it.
new_list = sorted(my_list) # Makes a sorted copy.
new_list = list(my_list) # Makes an exact copy.