Lists
Introduction
A list is an ordered collection of objects of any type. You can have lists of floats, strings, objects made from classes you've defined, and more. You can even have lists contain other lists. You're allowed to mix the types of objects in a list, for example you can have a list that contains both integers and strings.
Most lists contain multiple values, but we can have lists of one or zero values, which can be useful. Run this cell to see a few lists.
The type hints are explained in the sections below. For now, notice two things. The hint on some_stuff is longer because that list mixes types. And the empty list zero still has a hint, because even an empty list needs to say what it could hold. We chose int for it.
Part 1: Creating and reading lists
The first half of this page covers how to write a list, how to give it a type hint, and how to read from it: its length, its items, slices, searching, and sorting, and how to combine two lists.
Type hinting with lists
Type hinting can be used to specify the expected data type of elements in a list. For example:
def get_average(numbers: list[float]) -> float:
return sum(numbers) / len(numbers)
In the example above, the get_average function takes a single argument, numbers, which is expected to be a list of float values. The list[float] syntax specifies that the numbers argument is a list whose elements are of type float. The function's return value is indicated to be of type float.
Here is how our examples look with type hinting added.
Check your understanding. Write a type hint. When every item in a list has the same type, the hint names the list and the type of its items, like list[int].
Replace the None below with a line that gives temperatures a type hint and the value [72.5, 68.0, 75.25].
Hint 1
The pattern is list[type of one item]. A number with a decimal point is a float.
Type hinting with mixed data types
To type hint a list with a mix of items, you can use the | operator, which lets you specify that a value can be one of several types. Read | as "or": int | str means an int or a str. Here is how we would type hint the some_stuff variable.
In this code, the some_stuff variable is declared as a list of items that can each be an int, a str, a float, or a nested list of str values, using the | operator.
Avoid the object type hint
If you want a list to hold anything at all, you can hint it as list[object]. Every value in Python is an object, so this is always accepted. That is the problem: it says nothing. Hinting something as object (or as Any, a similar type you may see in other code that also means "anything") is a code smell, a sign that the code could be clearer or safer. Use it only as a last resort.
- A type checker can no longer catch mistakes. It only knows that each item is "something", so it cannot confirm that
some_stuff[1].upper()is safe, and it cannot warn thatsome_stuff[0].upper()will crash. - A reader cannot tell what the list is supposed to hold without reading all the code that fills it.
Run this to see the smell. The program works, but the hint on the first line gives no help.
Here is the better version. It says exactly which types the list holds, as in the previous section:
Better still, when you control the data, is to avoid a mixed list. A list where every item has the same type is easier to hint, to read and to use:
Check your understanding. Write a harder type hint. This list mixes several types, and one of its items is itself a list. Name every type that can appear, joined with |. Do not use object.
Replace the None below with a line that gives entry a type hint and the value ["Mira", 7, True, [4, 9, 2]].
Hint 1
Put the types of the four kinds of item inside list[...], joined with |. The inner list holds ints, so its type is list[int].
len
With lists, len() returns the number of elements in the list:
Indexing and slicing
Indexing and slicing work the same with lists as they do with strings. Try these examples one at a time.
When you index into a nested list to get a sublist, you can then index into that list. Try the following to get the list within some_stuff, then the item "Tollbooth" within that sublist, and then its first character:
An index must point at an item that exists. A list with five items has indexes 0 to 4, and asking for anything outside that range stops the program with an IndexError. Slices are gentler: a slice that reaches past the end just gives back what is there.
The last valid index is 4, so some_names[5] raises an IndexError. Change 5 to -1 to get the last item, and run it again.
Check your understanding. Predict the result. Negative indexes count from the end, and a slice that runs past the end does not raise an error.
letters: list[str] = ["a", "b", "c", "d", "e"]
last: str = letters[-1]
middle: list[str] = letters[1:3]
rest: list[str] = letters[3:10]
Predict what each variable holds after the program finishes. The program is not run for you. Replace each None in the box below with your prediction, and give each variable a type hint, like name: type = value. Then press Run to find out if you are right. Write text in quotes, like "abc". Write a list in square brackets, like ["x", "y"].
final_lastis the value oflastat the endfinal_middleis the value ofmiddleat the endfinal_restis the value ofrestat the end
Hint 1
For the slice [1:3], take index 1 up to but not including index 3. For [3:10], take everything from index 3 until the list runs out.
in, not in
Also like strings, we can use in and not in. With these two operators, the second operand can be a string or a list, and the first operand can be any value. Try these examples to see for yourself:
What happened with those last two examples? The string "Phantom" is not in some_stuff. It's in a list that's in some_stuff. That list is at index 3, so we were able to find it there.
Let's look at some more things we can do, with new list examples.
min and max, sort
There are min and max functions we can use. Try these:
The min and max functions wouldn't make sense for a list like some_stuff, since Python doesn't know how to compare the different types in that list. There's also a sort method we can use.
You'll notice that nothing prints out when you try those. But now look at the lists again:
The sort method works "in place": it changes the original list. Sorting also wouldn't make sense for some_stuff, again because Python doesn't know how to compare the different types in that list. Try it and see!
Check your understanding. Predict the result. Look at what sort gives back.
nums: list[int] = [3, 1, 2]
result = nums.sort()
Predict what each variable holds after the program finishes. The program is not run for you. Replace each None in the box below with your prediction, and give each variable a type hint, like name: type = value. Then press Run to find out if you are right. Write text in quotes, like "abc". Write a list in square brackets, like [1, 2, 3].
final_numsis the value ofnumsat the endfinal_resultis the value ofresultat the end
Hint 1
Some list methods change the list itself instead of making a new one. Ask what sort hands back.
Concatenation
We can concatenate lists with the + operator.
Here's one more list example for us to practice on.
Check your understanding. Predict the result. One of these changes a list and one makes a new one.
a: list[int] = [1, 2]
b: list[int] = a + [3]
a[0] = 9
Predict what each variable holds after the program finishes. The program is not run for you. Replace each None in the box below with your prediction, and give each variable a type hint, like name: type = value. Then press Run to find out if you are right. Write text in quotes, like "abc". Write a list in square brackets, like [1, 2, 3].
final_ais the value ofaat the endfinal_bis the value ofbat the end
Hint 1
Adding two lists builds a new list. After each line, ask which names refer to which list.
Explanation
The stop index is not included. A step of -1 walks backward.
Part 2: Working through lists
The second half covers going through a list one item at a time, lists that hold objects of your own classes, and building new lists from old ones.
Iterating through a List
Lists are iterable, so we can use a for loop to access each element. For example, try this loop:
The following loop prints out a running total of the values in the list:
Lists of objects
Let's reintroduce the BankAccount class we defined in an earlier section:
We can make a list of BankAccount objects like this:
What if we want to access the balance of the first account in the list? We can do that like this:
Here account_list[0] gives us a BankAccount object, and .get_balance() returns the balance of that object.
List Comprehensions
List comprehensions are a concise way to construct a new list by applying some transformation to an existing list. Anything you can loop over, such as a list or a range, is called an iterable. For example, the following code creates a new list whose elements are double the elements in fun_floats (defined earlier):
Here's a similar example that works from a range instead of a list:
We can optionally filter out certain values from the original list (or other iterable).
In this example, the original iterable was a range. If a value in that range is odd (the remainder of dividing by 2 is 1), then we apply the transformation (multiplying by 2). Note that values are filtered out before the transformation is applied. If we had doubled the numbers and then filtered out the even ones, then the new list would have been empty.
We can also use a list comprehension to filter without applying a transformation:
These uses of for and if are related to loops and conditionals, but they build a list in one expression. The quizzes below are where it clicks.
Quizzes
- Write a function named
every_otherthat takes a list as a parameter and returns a list that contains only every other element starting with the first one. For example, if the original list is[7, "joe", "apple", 9.81, False], then the new list should be[7, "apple", False]. Use slicing.
- Write a function named
array_sumthat takes a list of strings as a parameter and returns the total number of characters in all the strings.
- Write a function named
rev_string_listthat takes a list of strings as a parameter and returns a list that contains the reverse of each of those strings. Use a list comprehension.
- Write a function named
contain_stringthat takes a list of strings and a target string as parameters, and returns a list of the strings from the original list that contain the target string. Use a list comprehension. As an example, if the function call iscontain_string(["cats", "tacks", "scat", "stack"], "cat"), then the return value should be["cats", "scat"], because"cats"and"scat"both contain"cat".
- Write a function named
last_twothat takes a list and returns a new list with its last two items. If the list has fewer than two items, return a list of all of its items. For example,last_two([4, 8, 15, 16])returns[15, 16]. Use slicing.
Hint 1
A negative index counts from the end, and a slice that reaches past the start does not raise an error.
- Write a function named
count_abovethat takes a list of numbers and a limit, and returns how many numbers in the list are greater than the limit. For example,count_above([3, 9, 5, 12], 4)returns3. Use a loop.
Hint 1
Start a counter at 0. Loop over the list, and add 1 each time a number is greater than the limit.
- The function below is meant to return a sorted version of a list, but it also reorders the list it was given. Run the code and read the message, then fix the function so the original list is left alone.
Hint 1
sort changes the list it is called on. Make a copy first, with a full slice such as items[:], and sort the copy.
Projects
Practice what you learned in your own editor. Each project has its own page.