Chapter 11
> 来源: Think Python 2e (Allen B. Downey)
> 原页: https://greenteapress.com/thinkpython/html/thinkpython011.html
\
------------------------------------------------------------------------
Chapter 10 Lists
10.1 A list is a sequence
Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in a list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and [):
[00000007
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:
[00000008
A list within another list is nested.
A list that contains no elements is called an empty list; you can create one with empty brackets, [0.
As you might expect, you can assign list values to variables:
[00000010
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:
[00000011
Unlike strings, lists are mutable. When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned.
[00000012
The one-eth element of [000000, which used to be 123, is now 5.
You can think of a list as a relationship between indices and elements. This relationship is called a mapping; each index “maps to” one of the elements. Figure 10.1 shows the state diagram for [000000, [000000 and [0000:
[插图缺失:thinkpython013.png]Figure 10.1: State diagram.
Lists are represented by boxes with the word “list” outside and the elements of the list inside. [000000 refers to a list with three elements indexed 0, 1 and 2. [000000 contains two elements; the diagram shows that the value of the second element has been reassigned from 123 to 5. [0000 refers to a list with no elements.
List indices work the same way as string indices:
- Any integer expression can be used as an index.
- If you try to read or write an element that does not exist, you get an
[00000020 . - If an index has a negative value, it counts backward from the end of the list.
The [0 operator also works on lists.
[00000022
10.3 Traversing a list
The most common way to traverse the elements of a list is with a [00 loop. The syntax is the same as for strings:
[00000024
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 functions [0000 and [00:
[00000027
This loop traverses the list and updates each element. [00 returns the number of elements in the list. [0000 returns a list of indices from 0 to n−1, where n is the length of the list. Each time through the loop [ gets the index of the next element. The assignment statement in the body uses [ to read the old value of the element and to assign the new value.
A [00 loop over an empty list never executes the body:
[00000033
Although a list can contain another list, the nested list still counts as a single element. The length of this list is four:
[00000034
10.4 List operations
The [ operator concatenates lists:
[00000036
Similarly, the [ operator repeats a list a given number of times:
[00000038
The first example repeats [00 four times. The second example repeats the list [00000040 three times.
10.5 List slices
The slice operator also works on lists:
[00000041
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you omit both, the slice is a copy of the whole list.
[00000042
Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle or mutilate lists.
A slice operator on the left side of an assignment can update multiple elements:
[00000043
10.6 List methods
Python provides methods that operate on lists. For example, [00000 adds a new element to the end of a list:
[00000045
[00000 takes a list as an argument and appends all of the elements:
[00000047
This example leaves [0 unmodified.
[000 arranges the elements of the list from low to high:
[00000050
List methods are all void; they modify the list and return [000. If you accidentally write [00000052 , you will be disappointed with the result.
10.7 Map, filter and reduce
To add up all the numbers in a list, you can use a loop like this:
[00000053
[0000 is initialized to 0. Each time through the loop, [ gets one element from the list. The [0 operator provides a short way to update a variable. This augmented assignment statement:
[00000057
is equivalent to:
[00000058
As the loop executes, [0000 accumulates the sum of the elements; a variable used this way is sometimes called an accumulator.
Adding up the elements of a list is such a common operation that Python provides it as a built-in function, [00:
[00000061
An operation like this that combines a sequence of elements into a single value is sometimes called reduce.
Exercise 1
Write a function called [00000062 that takes a nested list of integers and add up the elements from all of the nested lists.
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:
[00000063
[00 is initialized with an empty list; each time through the loop, we append the next element. So [00 is another kind of accumulator.
An operation like [00000066 is sometimes called a map because it “maps” a function (in this case the method [00000067 ) onto each of the elements in a sequence.
Exercise 2
Use [00000068 to write a function named [00000069 that takes a nested list of strings and returns a new nested list with all strings capitalized.
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:
[00000070
[000000 is a string method that returns [000 if the string contains only upper case letters.
An operation like [00000073 is called a filter because it selects some of the elements and filters out the others.
Most common list operations can be expressed as a combination of map, filter and reduce. Because these operations are so common, Python provides language features to support them, including the built-in function [00 and an operator called a “list comprehension.”
Exercise 3
Write a function 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, the cumulative sum of [00000075 is [00000076.
10.8 Deleting elements
There are several ways to delete elements from a list. If you know the index of the element you want, you can use [00:
[00000078
[00 modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element.
If you don’t need the removed value, you can use the [00 operator:
[00000081
If you know the element you want to remove (but not the index), you can use [00000:
[00000083
The return value from [00000 is [000.
To remove more than one element, you can use [00 with a slice index:
[00000087
As usual, the slice selects all the elements up to, but not including, the second index.
Exercise 4
Write a function called [00000 that takes a list and returns a new list that contains all but the first and last elements. So [00000089 should return [0000.
Exercise 5
Write a function called [000 that takes a list, modifies it by removing the first and last elements, and returns [000.
10.9 Lists and strings
A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use [000:
[00000094
Because [000 is the name of a built-in function, you should avoid using it as a variable name. I also avoid [ because it looks too much like [. So that’s why I use [.
The [000 function breaks a string into individual letters. If you want to break a string into words, you can use the [0000 method:
[00000101
An optional argument called a delimiter specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter:
[00000102
[000 is the inverse of [0000. It takes a list of strings and concatenates the elements. [000 is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:
[00000106
In this case the delimiter is a space character, so [000 puts a space between words. To concatenate strings without spaces, you can use the empty string, [0, as a delimiter.
10.10 Objects and values
If we execute these assignment statements:
[00000109
We know that [ and [ 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.
[插图缺失:thinkpython014.png]Figure 10.2: State diagram.
In one case, [ and [ refer to two different objects that have the same value. In the second case, they refer to the same object.
To check whether two variables refer to the same object, you can use the [0 operator.
[00000115
In this example, Python only created one string object, and both [ and [ refer to it.
But when you create two lists, you get two objects:
[00000118
So the state diagram looks like Figure 10.3.
[插图缺失:thinkpython015.png]Figure 10.3: State diagram.
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 execute [000001, 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.
10.11 Aliasing
If [ refers to an object and you assign [0000, then both variables refer to the same object:
[00000122
The state diagram looks like Figure 10.4.
[插图缺失:thinkpython016.png]Figure 10.4: State diagram.
The association of a variable with an object is called a reference. In this example, there are two references to the same object.
An object with more than one reference has more than one name, so we say that the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:
[00000123
Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when you are working with mutable objects.
For immutable objects like strings, aliasing is not as much of a problem. In this example:
[00000124
It almost never makes a difference whether [ and [ 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 a list parameter, the caller sees the change. For example, [00000127 removes the first element from a list:
[00000128
Here’s how it is used:
[00000129
The parameter [ and the variable [000001 are aliases for the same object. The stack diagram looks like Figure 10.5.
[插图缺失:thinkpython017.png]Figure 10.5: Stack diagram.
Since the list is shared by two frames, I drew it between them.
It is important to distinguish between operations that modify lists and operations that create new lists. For example, the [00000 method modifies a list, but the [ operator creates a new list:
[00000134
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:
[00000135
The slice operator creates a new list and the assignment makes [ refer to it, but none of that has any effect on the list that was passed as an argument.
An alternative is to write a function that creates and returns a new list. For example, [000 returns all but the first element of a list:
[00000138
This function leaves the original list unmodified. Here’s how it is used:
[00000139
10.13 Debugging
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:
- Don’t forget that most list methods modify the argument and return
[000. This is the opposite of the string methods, which return a new string and leave the original alone.If you are used to writing string code like this:
[00000141It is tempting to write list code like this:
[00000142Because
[000 returns[000, the next operation you perform with[is likely to fail.Before using list methods and operators, you should read the documentation carefully and then test them in interactive mode. The methods and operators that lists share with other sequences (like strings) are documented at
[00000146 . The methods and operators that only apply to mutable sequences are documented at[00000147 . - Pick an idiom and stick with it.
Part of the problem with lists is that there are too many ways to do things. For example, to remove an element from a list, you can use
[00,[00000,[00, or even a slice assignment.To add an element, you can use the
[00000 method or the[operator. Assuming that[is a list and[is a list element, these are right:[00000155And these are wrong:
[00000156Try out each of these examples in interactive mode to make sure you understand what they do. Notice that only the last one causes a runtime error; the other three are legal, but they do the wrong thing.
- Make copies to avoid aliasing.
If you want to use a method like
[000 that modifies the argument, but you need to keep the original list as well, you can make a copy.[00000158In this example you could also use the built-in function
[00000, which returns a new, sorted list and leaves the original alone. But in that case you should avoid using[00000 as a variable name!
10.14 Glossary
- list:
-
A sequence of values.
- element:
-
One of the values in a list (or other sequence), also called items.
- index:
-
An integer value that indicates an element in a list.
- nested list:
-
A list that is an element of another list.
- list traversal:
-
The sequential accessing of each element in a list.
- mapping:
-
A relationship in which each element of one set corresponds to an element of another set. For example, a list is a mapping from indices to elements.
- accumulator:
-
A variable used in a loop to add up or accumulate a result.
- augmented assignment:
-
A statement that updates the value of a variable using an operator like
[0. - reduce:
-
A processing pattern that traverses a sequence and accumulates the elements into a single result.
- map:
-
A processing pattern that traverses a sequence and performs an operation on each element.
- filter:
-
A processing pattern that traverses a list and selects the elements that satisfy some criterion.
- object:
-
Something a variable can refer to. An object has a type and a value.
- equivalent:
-
Having the same value.
- identical:
-
Being the same object (which implies equivalence).
- reference:
-
The association between a variable and its value.
- aliasing:
-
A circumstance where two or more variables refer to the same object.
- delimiter:
-
A character or string used to indicate where a string should be split.
10.15 Exercises
Exercise 6 Write a function called [00000162 that takes a list as a parameter and returns [000 if the list is sorted in ascending order and [0000 otherwise. You can assume (as a precondition) that the elements of the list can be compared with the relational operators [000, [000, etc.
For example, [00000167 should return [000 and [00000169 should return [0000.
Exercise 7
Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function called [00000171 that takes two strings and returns [000 if they are anagrams.
Exercise 8
The (so-called) Birthday Paradox:
- Write a function called
[00000173 that takes a list and returns[000 if there is any element that appears more than once. It should not modify the original list. - If there are 23 students in your class, what are the chances that two of you 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
[000001 function in the[00000 module.
You can read about this problem at [00000177 , and you can download my solution from [00000178 .
Exercise 9
Write a function called [00000179 that takes a list and returns a new list with only the unique elements from the original. Hint: they don’t have to be in the same order.
Exercise 10
Write a function that reads the file [00000180 and builds a list with one element per word. Write two versions of this function, one using the [00000 method and the other using the idiom [00000182 . Which one takes longer to run? Why?
Hint: use the [000 module to measure elapsed time. Solution: [00000184 .
Exercise 11
To check whether a word is in the word list, you could use the [0 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. 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, then 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.
Write a function called [00000 that takes a sorted list and a target value and returns the index of the value in the list, if it’s there, or [000 if it’s not.
Or you could read the documentation of the [00000 module and use that! Solution: [00000189 .
Exercise 12
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: [00000190 .
Exercise 13
Two words “interlock” if taking alternating letters from each forms a new word. For example, “shoe” and “cold” interlock to form “schooled.” Solution: [00000191 . Credit: This exercise is inspired by an example at [00000192 .
- Write a program that finds all pairs of words that interlock. Hint: don’t enumerate all pairs!
- Can you find any words that are three-way interlocked; that is, every third letter forms a word, starting from the first, second or third?
Contribute
If you would like to make a contribution to support my books, you can use the button below. Thank you!
Pay what you want:
Small $1.00 USD Medium $5.00 USD Large $10.00 USD X-Large $20.00 USD XX-Large $50.00 USD
Are you using one of our books in a class?
We'd like to know about it. Please consider filling out this short survey.
------------------------------------------------------------------------
\
---