Lists
What is a list?
So far we've learned about strings and numbers, two essential data types in Python. They allow us to store any characters that we want to come back to, and also to do mathematical operations.
However, sometimes we need to store many things and we want to be able to easily use that group of things. For example, we could want to store a list of our friends, our books, or even the types of coffee we've tried.
As soon as we start wanting to deal with multiple different things, many students initially turn to defining many variables, like this:
friend1 = "Rolf"
friend2 = "Bob"
friend3 = "Anne"
However, this poses a few problems.
- First, that your program becomes tied to this style of variable definition. What happens if you want to add more friends?
- Second, that allowing your program to grow becomes difficult. What if you want to add 100 friends?
- Third, that performing operations on all friends becomes difficult. For example, what if you wanted to print out friend names that start with
"B"
?
Using lists we solve all these problems, because we will have a single variable that contains all of the strings.
We would define a list containing those three friend names like so:
friends = ["Rolf", "Bob", "Anne"]
Note the use of square brackets denotes a list, and inside it we can place many values. Each value is separated from other values by commas.
We still can access individual friend names if we want by using subscript notation (square brackets after the variable name):
friends = ["Rolf", "Bob", "Anne"]
print(friends[0]) # Rolf
print(friends[1]) # Bob
Remember that in programming we start counting from 0, so the element with index 0 is really the first element of the list.
Using lists we also unlock the ability to perform operations on all (or a subset) of students. We will learn more about how to do that in the coming chapters!
What can you store in a list?
You can store anything you want in a list. Each element of the list can be a string or a number. You can have both strings and numbers in the same list, like so:
friends = ["Rolf", 2, "Anne"]
However, it is generally recommended that lists only store one type of thing per list. You can see that calling our list friends
and storing the value 2
in it can quickly get confusing. What does 2
mean? Is it the name of a friend? Or is it something else?
Let's imagine the 2
is the number of friends you have. It's much better to use Python to calculate it, and not put it inside a list that is supposed to contain friend names.
Instead, just keep your friend names in the list:
friends = ["Rolf", "Anne"]
print(len(friends)) # 2
Here we used the len()
function. If we put our list inside the brackets, it tells us the length of the list—or how many elements are in it.
As with all variables, giving your variable a good, descriptive name will go a long way. Make sure that the contents of the variable are reflective of what the name says!
Don't do this:
friends = ["Chair", "Table", "Lamp"]
In the example above, we can imagine that the programmer started off writing a program about his or her friends—but after defining the variable, they decided to write about furniture instead. They didn't change the name of the variable, and now the program is really confusing.
Lists inside lists
You can put lists inside lists if you want. For example, that would allow us to store friends and some information about them (though we'll learn an even better way in the next chapter):
friends = [["Rolf", 24], ["Bob", 30], ["Anne", 27]]
Here you can assume that the second element of each sub-list is the friend's age. Remember that you have one list with three lists inside it. If you wanted Rolf's age:
print(friends[0][1]) # 24
print(friends[1][0]) # Bob
If you try to access a key that doesn't exist, such as friends[0][2]
, Python will tell you that it doesn't exist with an error that looks like this:
IndexError: list index out of range
If you see that, it means your program tried accessing an index that doesn't exist. Double check your code by walking through it line by line!
Long lists
When your lists start getting longer, Python accepts splitting it into multiple lines so that your lines don't become overly long. Usually I would write lists like the one above like this:
friends = [
["Rolf", 24],
["Bob", 30],
["Anne", 27]
]
How do you add things to a list?
Once you have your list, you can append things to it. Appending means adding something at the end of the list:
friends = ["Rolf", "Bob", "Anne"]
friends.append("Jen")
print(friends) # ["Rolf", "Bob", "Anne", "Jen"]
Of course, you can .append()
anything you want—since a list can contain any type of element.
For example:
friends = ["Rolf", "Bob", "Anne"]
friends.append(["Hello", "World"])
print(friends) # ["Rolf", "Bob", "Anne", ["Hello", "World"]]
Of course, doing that may or may not be useful in your program!
How do you remove things from a list?
You can always remove something from a list, but it can be a bit tricky to do in some cases. I almost never have to remove things from a list, but I'll teach you how to do it anyway:
friends = ["Rolf", "Bob", "Anne"]
friends.remove("Bob")
print(friends) # ["Rolf", "Anne"]
If your list contains strings or numbers, it's as easy as that. There are occasions where it's not as simple, and we'll learn about those later on in the course!
Remember that if you have a list of lists, you'll need to tell .remove()
everything the exact thing you want to delete:
friends = [
["Rolf", 24],
["Bob", 30],
["Anne", 27]
]
friends.remove(["Bob", 30])
Common pitfalls
How do you copy a list?
Imagine you want two lists: one for your nearby friends and one for your friends who are abroad. You could make a list of all your friends, and then copy it.
Then you could take away from the first list those friends that are nearby. It's quite common for students to try something like this:
friends = ["Rolf", "Bob", "Anne"]
friends_abroad = friends
friends_abroad.remove("Bob")
However, that does not work.
Because we made friends_abroad = friends
, they're actually the same list. When you remove from one, you remove from the other:
print(friends) # ["Rolf", "Anne"]
What we want to do in this case is make a copy of the list, instead of using the same one. You can do this like so:
friends = ["Rolf", "Bob", "Anne"]
friends_abroad = friends.copy()
friends_abroad.remove("Bob")
Lists in lists
When you do something like friends.copy()
you're performing what's called a shallow copy. A shallow copy means that the outer-most list is now different, but any inner lists that are present are still the same as in the initial variable.
It's difficult to explain, so let's jump to some code!
friends = [
["Rolf", 24],
["Bob", 30],
["Anne", 27]
]
friends_abroad = friends.copy()
print(friends_abroad[1][0]) # Bob
friends_abroad[1][0] = "Jen"
print(friends_abroad[1][0]) # Jen
print(friends[1][0]) # Jen
In this example we had a list of lists. We then copied it and tried to modify one of the inner lists (friends_abroad[1][0]
).
This modified both the copied and the non-copied list, because when we did .copy()
we only copied the outermost list, and not the inner lists. Those lists still are the same list so changing one changes the other.
My advice regarding copying lists would be to be very careful about whether you really need to copy a list or not. Creating a new list is often the best approach—something like this:
friends_nearby = ["Rolf", "Bob"]
friends_abroad = ["Anne"]
Now you have no problem!