2. List Methods

Quick Overview of Day

Explore methods that allow you to manipulate lists.

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

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

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.

2.7.2. List Methods Practice

Given my_list below, write Python statements to do the following:

  1. Append “apple” and 76 to the list.

  2. Insert the value “cat” at position 3.

  3. Insert the value 99 at the start of the list.

  4. Find the index of “hello”.

  5. Count the number of 76s in the list.

  6. Remove the first occurrence of 76 from the list.

  7. Remove the last element from the list, and print it’s value.

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:

  1. count

  2. in

  3. reverse

  4. index

  5. insert

Next Section - 3. Lists and Turtle Drawing