Chapter 10 Lists
This chapter presents one of Python’s most useful built-in types, lists. You will also learn more about objects and what can happen when you have more than one name for the same object.
10.1 A list is a sequence
There are several ways to create a new list; the simplest is to
enclose the elements in square brackets (
[10, 20, 30, 40] ['crunchy frog', 'ram bladder', 'lark vomit']
The first example is a list of four integers. The second is a list of three strings. The elements of a list don’t have to be the same type. The following list contains a string, a float, an integer, and (lo!) another list:
['spam', 2.0, 5, [10, 20]]
As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda'] >>> numbers = [42, 123] >>> empty =  >>> print(cheeses, numbers, empty) ['Cheddar', 'Edam', 'Gouda'] [42, 123] 
10.2 Lists are mutable
The syntax for accessing the elements of a list is the same as for accessing the characters of a string—the bracket operator. The expression inside the brackets specifies the index. Remember that the indices start at 0:
>>> cheeses 'Cheddar'
>>> numbers = [42, 123] >>> numbers = 5 >>> numbers [42, 5]
Figure 10.1 shows the state diagram for cheeses, numbers and empty.
Lists are represented by boxes with the word “list” outside and the elements of the list inside. cheeses refers to a list with three elements indexed 0, 1 and 2. numbers contains two elements; the diagram shows that the value of the second element has been reassigned from 123 to 5. empty refers to a list with no elements.
List indices work the same way as string indices:
The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda'] >>> 'Edam' in cheeses True >>> 'Brie' in cheeses False
10.3 Traversing a list
The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings:
for cheese in cheeses: print(cheese)
This works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to do that is to combine the built-in functions range and len:
for i in range(len(numbers)): numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element. len returns the number of elements in the list. range returns a list of indices from 0 to n−1, where n is the length of the list. Each time through the loop i gets the index of the next element. The assignment statement in the body uses i to read the old value of the element and to assign the new value.
A for loop over an empty list never runs the body:
for x in : print('This never happens.')
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
10.4 List operations
>>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> c [1, 2, 3, 4, 5, 6]
>>>  * 4 [0, 0, 0, 0] >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats  four times. The second example repeats the list [1, 2, 3] three times.
10.5 List slices
The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] ['b', 'c'] >>> t[:4] ['a', 'b', 'c', 'd'] >>> t[3:] ['d', 'e', 'f']
>>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']
>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] = ['x', 'y'] >>> t ['a', 'x', 'y', 'd', 'e', 'f']
10.6 List methods
>>> t = ['a', 'b', 'c'] >>> t.append('d') >>> t ['a', 'b', 'c', 'd']
>>> t1 = ['a', 'b', 'c'] >>> t2 = ['d', 'e'] >>> t1.extend(t2) >>> t1 ['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified.
>>> t = ['d', 'c', 'e', 'b', 'a'] >>> t.sort() >>> t ['a', 'b', 'c', 'd', 'e']
10.7 Map, filter and reduce
To add up all the numbers in a list, you can use a loop like this:
def add_all(t): total = 0 for x in t: total += x return total
total += x
is equivalent to
total = total + x
Adding up the elements of a list is such a common operation that Python provides it as a built-in function, sum:
>>> t = [1, 2, 3] >>> sum(t) 6
Sometimes you want to traverse one list while building another. For example, the following function takes a list of strings and returns a new list that contains capitalized strings:
def capitalize_all(t): res =  for s in t: res.append(s.capitalize()) return res
Another common operation is to select some of the elements from a list and return a sublist. For example, the following function takes a list of strings and returns a list that contains only the uppercase strings:
def only_upper(t): res =  for s in t: if s.isupper(): res.append(s) return res
isupper is a string method that returns True if the string contains only upper case letters.
An operation like
Most common list operations can be expressed as a combination of map, filter and reduce.
10.8 Deleting elements
>>> t = ['a', 'b', 'c'] >>> x = t.pop(1) >>> t ['a', 'c'] >>> x 'b'
pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element.
>>> t = ['a', 'b', 'c'] >>> del t >>> t ['a', 'c']
>>> t = ['a', 'b', 'c'] >>> t.remove('b') >>> t ['a', 'c']
To remove more than one element, you can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> del t[1:5] >>> t ['a', 'f']
As usual, the slice selects all the elements up to but not including the second index.
10.9 Lists and strings
>>> s = 'spam' >>> t = list(s) >>> t ['s', 'p', 'a', 'm']
Because list is the name of a built-in function, you should avoid using it as a variable name. I also avoid l because it looks too much like 1. So that’s why I use t.
>>> s = 'pining for the fjords' >>> t = s.split() >>> t ['pining', 'for', 'the', 'fjords']
>>> s = 'spam-spam-spam' >>> delimiter = '-' >>> t = s.split(delimiter) >>> t ['spam', 'spam', 'spam']
>>> t = ['pining', 'for', 'the', 'fjords'] >>> delimiter = ' ' >>> s = delimiter.join(t) >>> s 'pining for the fjords'
10.10 Objects and values
If we run these assignment statements:
a = 'banana' b = 'banana'
We know that a and b both refer to a string, but we don’t know whether they refer to the same string. There are two possible states, shown in Figure 10.2.
To check whether two variables refer to the same object, you can use the is operator.
>>> a = 'banana' >>> b = 'banana' >>> a is b True
In this example, Python only created one string object, and both a and b refer to it. But when you create two lists, you get two objects:
>>> a = [1, 2, 3] >>> b = [1, 2, 3] >>> a is b False
So the state diagram looks like Figure 10.3.
In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.
Until now, we have been using “object” and “value” interchangeably, but it is more precise to say that an object has a value. If you evaluate [1, 2, 3], you get a list object whose value is a sequence of integers. If another list has the same elements, we say it has the same value, but it is not the same object.
If a refers to an object and you assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3] >>> b = a >>> b is a True
The state diagram looks like Figure 10.4.
If the aliased object is mutable, changes made with one alias affect the other:
>>> b = 42 >>> a [42, 2, 3]
For immutable objects like strings, aliasing is not as much of a problem. In this example:
a = 'banana' b = 'banana'
It almost never makes a difference whether a and b refer to the same string or not.
10.12 List arguments
When you pass a list to a function, the function gets a reference to
the list. If the function modifies the list, the caller sees
the change. For example,
def delete_head(t): del t
Here’s how it is used:
>>> letters = ['a', 'b', 'c'] >>> delete_head(letters) >>> letters ['b', 'c']
The parameter t and the variable letters are aliases for the same object. The stack diagram looks like Figure 10.5.
Since the list is shared by two frames, I drew it between them.
Here’s an example using append:
>>> t1 = [1, 2] >>> t2 = t1.append(3) >>> t1 [1, 2, 3] >>> t2 None
The return value from append is None.
Here’s an example using the + operator:
>>> t3 = t1 +  >>> t1 [1, 2, 3] >>> t3 [1, 2, 3, 4]
The result of the operator is a new list, and the original list is unchanged.
This difference is important when you write functions that are supposed to modify lists. For example, this function does not delete the head of a list:
def bad_delete_head(t): t = t[1:] # WRONG!
>>> t4 = [1, 2, 3] >>> bad_delete_head(t4) >>> t4 [1, 2, 3]
At the beginning of
An alternative is to write a function that creates and returns a new list. For example, tail returns all but the first element of a list:
def tail(t): return t[1:]
This function leaves the original list unmodified. Here’s how it is used:
>>> letters = ['a', 'b', 'c'] >>> rest = tail(letters) >>> rest ['b', 'c']
Careless use of lists (and other mutable objects) can lead to long hours of debugging. Here are some common pitfalls and ways to avoid them:
You can download solutions to these exercises from http://thinkpython2.com/code/list_exercises.py.
Write a function called
>>> t = [[1, 2], , [4, 5, 6]] >>> nested_sum(t) 21
Write a function called cumsum that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i+1 elements from the original list. For example:
>>> t = [1, 2, 3] >>> cumsum(t) [1, 3, 6]
Write a function called
>>> t = [1, 2, 3, 4] >>> middle(t) [2, 3]
Write a function called
>>> t = [1, 2, 3, 4] >>> chop(t) >>> t [2, 3]
Exercise 5 Write a function called
>>> is_sorted([1, 2, 2]) True >>> is_sorted(['b', 'a']) False
Two words are anagrams if you can rearrange the letters from one
to spell the other. Write a function called
Write a function called
This exercise pertains to the so-called Birthday Paradox, which you can read about at http://en.wikipedia.org/wiki/Birthday_paradox.
If there are 23 students in your class, what are the chances that two of them have the same birthday? You can estimate this probability by generating random samples of 23 birthdays and checking for matches. Hint: you can generate random birthdays with the randint function in the random module.
You can download my solution from http://thinkpython2.com/code/birthday.py.
Write a function that reads the file words.txt and builds a list with one element per word. Write two versions of this function, one using the append method and the other using the idiom t = t + [x]. Which one takes longer to run? Why?
To check whether a word is in the word list, you could use the in operator, but it would be slow because it searches through the words in order.
Because the words are in alphabetical order, we can speed things up with a bisection search (also known as binary search), which is similar to what you do when you look a word up in the dictionary (the book, not the data structure). You start in the middle and check to see whether the word you are looking for comes before the word in the middle of the list. If so, you search the first half of the list the same way. Otherwise you search the second half.
Either way, you cut the remaining search space in half. If the word list has 113,809 words, it will take about 17 steps to find the word or conclude that it’s not there.
Or you could read the documentation of the bisect module and use that! Solution: http://thinkpython2.com/code/inlist.py.
Two words are a “reverse pair” if each is the reverse of the other. Write a program that finds all the reverse pairs in the word list. Solution: http://thinkpython2.com/code/reverse_pair.py.
Two words “interlock” if taking alternating letters from each forms a new word. For example, “shoe” and “cold” interlock to form “schooled”. Solution: http://thinkpython2.com/code/interlock.py. Credit: This exercise is inspired by an example at http://puzzlers.org.
ContributeIf you would like to make a contribution to support my books, you can use the button below and pay with PayPal. Thank you!
Are you using one of our books in a class?We'd like to know about it. Please consider filling out this short survey.