Concepts:Chapter 7
|
Method | Example/Description |
append(item) | list_name.append(item)
Calls the append() method of a list to add a new item to the end of the list. |
index(item) | list_name.index(item) Calls the index() method of a list, which will return the index of the first instance of a specified value. Note: this will raise an exception if the value is not found, so you may want to verify that the item is in the list first. |
insert(index, item) | list_name.insert(index, item) Calls the insert() method of a list, which inserts the new item at the specified index. The existing item at that index is moved to the next higher index, and the same is done for each of the other items in the list that were to the right of the insertion position. |
sort() | list_name.sort() Calls the sort() method of a list, which reorders the items in the list according to the rules for < and >. Note that this changes the actual list, not a copy in a variable. If you want to retain the original order, make a copy first. |
remove(item) | list_name.remove(item) Calls the remove() method of a list, which finds and deletes the first instance of the specified value in the list. Items in the list that followed the removed item are reassigned new indexes, starting with the index of the removed item. Note: this will raise an exception if the value is not found, so you may want to verify that the item is in the list first. |
reverse() | list_name.reverse() Calls the reverse() method of a list, which reverses the order of the elements in the list. Note that this changes the actual list, not a copy in a variable. If you want to retain the original order, make a copy first. (See below.) |
The text discusses three more tools that are useful with lists:
Copying Lists
Making a copy of a
list is more difficult that you might think. Before we start, think
about this: what is a list?
When we are working with a list in a program, a list is a set of values stored in memory.
Consider this example:
list1 = ['a', 'b', 'c']
list2 = list1
The text informs us that the code in the lines above will create and populate list1, then set the label list2 to point to the same list in memory. The new list name, list2, does not create a new list. Essentially, this code simply creates an alternate name for the same list.
The text then shows us two ways to make an actual copy of a list. The first way is to use a loop and a list method. It could look like this:
list1 = ['a', 'b', 'c']
list2 = [] # this creates an empty list
for item in list1
list2.append(item) # this
method appends each item from list1 to list2, and it avoids having to
write to indexes that do not exist in the empty
list
Another way would have been to measure the length of list1, create a new list with the same number of (dummy) elements, then loop through list1, copying the value of each indexed element to the corresponding element in list2. The second way the text shows us is shorter, but the result is the same:
list1 = ['a', 'b', 'c']
list2 = [] + list1
# this creates a new empty list,
then appends the contents of
list1 to the new list
In both methods above, a new empty list is created first. This is a necessary step if we want there to be two actual lists in memory when we are done.
Processing Lists
The text remarks on the usefulness of using a constant for the number of employees, since it makes it very easy to change that one line of the program to accommodate a change in that number.
The text shows us an example of a program that runs through a
list of numbers and calculates their total.
This is done again in the next program example, but this time the
program calculates the average
of the numbers (mean,
actually), by using the len() function
to count the number of elements in the list.
The text pauses to consider how you might pass a list to a function as an argument.
Having asked the question, you may be disappointed that there is no
trick to it. You simply pass the name of the list and receive it in the
called function as you would pass and receive any variable. It works
the same way when a list is created and populated in a called function.
That function can return the name of the list, and it will be
accessible by the calling function.
The text introduces a file object method called writelines(), which can be used to write a list to a file. In example program 7-13, writelines.py, the program creates a list, cities, that holds four strings. It then opens a file, cities.txt, in w mode. It then calls the writelines method of the file object, outfile, to write the list to the file:
outfile.writelines(cities)
The file is then closed, and that example is done. The problem with that method is that the data goes into the file as one string, without any clue to where the individual strings should break. The text presents an alternative method: use a loop that can use the file object write() method to write each element of the list, concatenated with a newline character, which will put each element on a line by itself. This works better for our purposes.
On page 322, we are introduced to the readlines() method of a file object. This method reads each line in a file, and returns a list of strings, each string being a single line. As we have seen before, we may or may not want the newline character that ends each string in the data. If we do not want it, there is an example in program 7-15 that uses the list's rstrip() method to strip off that trailing character from each string in the list. Program 7-16 does the reverse: it takes a list of numbers, turns them into strings, concatenates a newline on each string, and writes each string to a file. Program 7-17 shows how to read all the lines in a file into a list, then run a loop to read each element, convert it to an int, then overwrite the string version with the int version in the list. We can talk about these examples in class.
Two-Dimensional Lists
We have seen lists in this chapter that held numbers, and lists that held strings. The text explains that any object can be an element in a list, including other lists. A two-dimensional list is just a list whose elements are also lists. The text shows us that printing any element of such a list will print the entire list that is stored at that element. That's nice, but what if we only wanted to access some of the elements of one of those nested lists? The text introduces an idea that leads to a notation that will let us access what we please.
In the example in the text, we start with a list called students. It holds three elements, each of which is a list of two students. The text represents this as a table with two columns, the size of the nested lists, and three rows, the number of lists in the outer list.
data held in students list |
element
0 in
nested list |
element
1 in
nested list |
element/nested
list 0 |
students[0][0] = 'Joe' |
students[0][1] = 'Kim' |
element/nested
list 1 |
students[1][0] = 'Sam' |
students[1][1] = 'Sue' |
element/nested
list 2 |
students[2][0] = 'Kelly' |
students[2][1] = 'Chris' |
Thinking about it this way, it should be more obvious why this kind of list is called two-dimensional. Each row holds one of the nested lists. Each column holds the elements at a particular position in one of the lists. As I have noted in the table, you can reference each element by the name of the two-dimensional list, followed by two subscripts, the first one for the row, and the second one for the column. Think of those as being like x and y coordinates on a graph. Horizontal reference first, then vertical reference. The text shows us another example, one having three columns, and three rows. Note that this still uses two coordinates, one for the row and one for the column. In program 7-18, the text shows us how to fill such a bunch of lists with two loops, one inside the other. The inner loop fills a row, while the outer loop controls what row is being filled. We could ask the user for a value, or we could do as the text does, generating a random value in each case.
Tuples
The last topic we will cover in this chapter is tuples. The text explains that a tuple is like a list, but it is immutable. Think of it as a list that is also a constant. There is a notation difference as well. The elements of a list are enclosed in square brackets. The elements of a tuple are enclose in parentheses. Example:
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
The text demonstrates looping through a tuple (to read it, because you can;t modify it) using two notations:
for n in my_tuple:
for n in range(len(my_tuple)):
The text tells us that tuples will support most of the things we can do with lists, but tuples do not contain these methods:
Showing some sensitivity to the reader, the text asks "what is the point of having tuples?" For some unspecified reason, you can process tuples faster to process than you can process lists. The author seems to like tuples because you can't change them, making them safer for testing. Maybe, but that still doesn't sound like a good reason to me.
Assignments |