2. List Methods¶
Quick Overview of Day
Explore methods that allow you to manipulate lists.
CS20-CP1 Apply various problem-solving strategies to solve programming problems throughout Computer Science 20.
CS20-FP1 Utilize different data types, including integer, floating point, Boolean and string, to solve programming problems.
CS20-FP2 Investigate how control structures affect program flow.
CS20-FP3 Construct and utilize functions to create reusable pieces of code.
CS20-FP4 Investigate one-dimensional arrays and their applications.
2.1. What Does This Program Do?¶
Note
Your teacher may choose to use the following examples as a class activity, by displaying the examples, and having you take a guess as to what you think each will do before running the code.
What will the following programs output? Why?
2.2. List Methods¶
The dot operator can also be used to access built-in methods of list objects.
append
is a list method which adds the argument passed to it to the end of
the list. Continuing with this example, we show several other list methods. Many of them are
easy to understand.
There are two ways to use the pop
method. The first, with no parameter, will remove and return the
last item of the list. If you provide a parameter for the position, pop
will remove and return the
item at that position. Either way the list is changed.
The following table provides a summary of the list methods shown above. The column labeled
result gives an explanation as to what the return value is as it relates to the new value of the list. The word
mutator means that the list is changed by the method but nothing is returned (actually None
is returned). A hybrid method is one that not only changes the list but also returns a value as its result. Finally, if the result is simply a return, then the list
is unchanged by the method.
Be sure to experiment with these methods to gain a better understanding of what they do.
Method |
Parameters |
Result |
Description |
---|---|---|---|
append |
item |
mutator |
Adds a new item to the end of a list |
insert |
position, item |
mutator |
Inserts a new item at the position given |
pop |
none |
hybrid |
Removes and returns the last item |
pop |
position |
hybrid |
Removes and returns the item at position |
sort |
none |
mutator |
Modifies a list to be sorted |
reverse |
none |
mutator |
Modifies a list to be in reverse order |
index |
item |
return idx |
Returns the position of first occurrence of item |
count |
item |
return ct |
Returns the number of occurrences of item |
remove |
item |
mutator |
Removes the first occurrence of item |
Details for these and others can be found in the Python Documentation.
It is important to remember that methods like append
, sort
,
and reverse
all return None
. This means that re-assigning my_list
to the result of sorting my_list
will result in losing the entire list. Calls like these will likely never appear as part of an assignment statement (see line 8 below).
2.2.1. Check Your Understanding¶
- [4, 2, 8, 6, 5, False, True]
- True was added first, then False was added last.
- [4, 2, 8, 6, 5, True, False]
- Yes, each item is added to the end of the list.
- [True, False, 4, 2, 8, 6, 5]
- append adds at the end, not the beginning.
list-methods11: What is printed by the following statements?
a_list = [4, 2, 8, 6, 5]
a_list.append(True)
a_list.append(False)
print(a_list)
- [4, 8, 6]
- pop(2) removes the item at index 2, not the 2 itself.
- [2, 6, 5]
- pop() removes the last item, not the first.
- [4, 2, 6]
- Yes, first the 8 was removed, then the last item, which was 5.
list-methods12: What is printed by the following statements?
a_list = [4, 2, 8, 6, 5]
temp = a_list.pop(2)
temp = a_list.pop()
print(a_list)
- [2, 8, 6, 5]
- a_list is now the value that was returned from pop(0).
- [4, 2, 8, 6, 5]
- pop(0) changes the list by removing the first item.
- 4
- Yes, first the 4 was removed from the list, then returned and assigned to a_list. The list is lost.
- None
- pop(0) returns the first item in the list so a_list has now been changed.
list-methods13: What is printed by the following statements?
a_list = [4, 2, 8, 6, 5]
a_list = a_list.pop(0)
print(a_list)
2.3. Inventory Example¶
If you were making a computer game, and you needed to keep track of what items the player was currently holding, using a list would be a good choice. At the beginning of the game, you might create an empty list, if the player begins the game without any items.
If the player obtains a new item, the new item should be added to the list. The easiest way to do this is to use the built-in .append()
method.
When you need to check if the player is currently able to perform a certain action, such as opening a locked door, you simply need to check if an item is in the inventory list.
Sometimes, the item the player uses might be something they can only use once. For example, after they used the “room 1 key”, we might want the “room 1 key” to no longer be in the player’s inventory. The following code does just that.
Note
Change the code above so you append a book
instead of a room 1 key
, then run the code again.
2.4. Shopping List¶
Say you want to make a list of things to buy when you go to the store. You could do something like this:
The obvious problem here is that we can only add one item to our list. Let’s put that logic into an infinite loop, so that we can continue to add items until we enter the word quit
:
2.5. Shakespearean Insult Generator¶
By importing other modules, you can add additional methods that can be used on lists. One example of this is from the random
module, which provides a choice
method that takes in a string, and returns one element of the list at random. Consider the following, which will pick a random name each time the code is executed:
The following is a simple insult generator, using words found in the works of the great bard.
2.6. Strings and Lists¶
Two of the most useful methods on strings involve lists of
strings. The split
method
breaks a string into a list of words. By
default, any number of whitespace characters is considered a word boundary.
An optional argument called a delimiter can be used to specify which
characters to use as word boundaries. The following example uses the string
ai
as the delimiter:
Notice that the delimiter doesn’t appear in the result.
The inverse of the split
method is join
. You choose a
desired separator string, (often called the glue)
and join the list with the glue between each of the elements.
The list that you glue together (word_list
in this example) is not modified. Also,
you can use empty glue or multi-character strings as glue.
2.6.1. Check Your Understanding¶
- Poe
- Three characters but not the right ones. name_list is the list of names.
- EdgarAllanPoe
- Too many characters in this case. There should be a single letter from each name.
- EAP
- Yes, split creates a list of the three names. The for loop iterates through the names and creates a string from the first characters.
- William Shakespeare
- That does not make any sense.
list-methods25: What is printed by the following statements?
my_name = "Edgar Allan Poe"
name_list = my_name.split()
some_string = ""
for a_name in name_list:
some_string = some_string + a_name[0]
print(some_string)
2.7. Practice Problems¶
2.7.1. Appending to a List¶
Create an empty list called my_list
. Now append the following items (one item at a time): 76, 92.3, “hello”, True, 4, 76.
my_list = []
my_list.append(76)
my_list.append(92.3)
my_list.append("hello")
my_list.append(True)
my_list.append(4)
my_list.append(76)
2.7.2. List Methods Practice¶
Given my_list
below, write Python statements to do the following:
Append “apple” and 76 to the list.
Insert the value “cat” at position 3.
Insert the value 99 at the start of the list.
Find the index of “hello”.
Count the number of 76s in the list.
Remove the first occurrence of 76 from the list.
Remove the last element from the list, and print it’s value.
my_list = [76, 92.3, 'hello', True, 4, 76]
my_list.append("apple") # a
my_list.append(76) # a
my_list.insert(3, "cat") # b
my_list.insert(0, 99) # c
print(my_list.index("hello")) # d
print(my_list.count(76)) # e
my_list.remove(76) # f
print(my_list.pop()) # g
print (my_list)
2.7.3. Compliment Generator¶
Those Shakespearean insults sting a bit. Let’s cheer everyone up by creating a random compliment generator. Your compliments should be in the style of “You are a great
friend
!”. Store any number of words similar to great
into a list called first_word_list
, and any number of words similar to friend
into a list called second_word_list
. Then pick one word from each of the lists at random, and print out a random compliment!
2.7.4. Averaging Random Integer List¶
Create a list containing 100 random integers between 0 and 1000 (use iteration, append, and the random module). Write a function called average that will take the list as a parameter and return the average.
2.7.5. Writing Your Own Methods¶
Although Python provides us with many list methods, it is good practice and very instructive to think about how they are implemented. Write Python functions that work like the following:
count
in
reverse
index
insert