9 Chapter 9: Lists and Dictionaries


0s and 1s on white background.


Topics Covered:

  • List basics
  • Slicing a list
  • Deleting from a list
  • Adding to a list
  • Processing a list
  • List operators


List basics

list is an ordered sequence of objects. You can use a list to store multiple items using a single variable. The Python list has many similarities to an array, which is provided by most programming languages. The main difference is that every item in an array must have the same data type while a list may contain objects of different types. If you know the values that you want to store in a list, you can create a list by enclosing the set of values, separated by commas, between square brackets, like this:

List to store multiple items.

The variable school now stores five data items associated with a university. Similar to a string, you can access individual elements of the list by using an index, or subscript. In the example below, we access the first element (using index 0) and the fourth element (using index 3). When attempting to access the element using index 5, Python indicates an error has occurred since the index is out of range:

Python code pulling things from the list in the previous image.

Python provides several statistical functions that come in handy when processing data in a list. In the code below, we create two more lists and then try out the len()max()min(), and sum() functions. These functions are pretty straightforward. As discussed in chapter three, the max and min of strings use ASCII codes. The program ran into trouble when it tried to find the sum() of a list of strings. The sum() function only works on numeric lists.

Two lists, one numeric and the other animals. The sum of the numbers is shown but the sum of the animals does not have a possible output.


Slicing a List

In the same way you can use square brackets [] and the colon (:) operator to extract slices of strings, you can retrieve slices of lists. The example below shows several slice examples. Examine each one closely to verify your understanding of how slices work.

Example showing the slicing of lists.

To further illustrate the concept of object-oriented programming, we will take a look at a couple of functions, or methods, that are associated with the list data type. As we saw when using methods for string variables, to use a method, you reference the list variable, followed by a dot, followed by the method name. Using the same nums list from previous examples, first we examine the count() method. You provide a value to the count() method as an argument, and it will return the number of occurrences of that value. The second example is the index() method. Again, you pass a value as an argument, but the index() method will return the position of that value in the list. If the value occurs multiple times, it returns the position of the first occurrence. If the value does not exist in the list, you can see from the example that it will cause the program to crash.

Example of count and index method.


Deleting from a List

There are two ways to remove an item from a list. You can use the del instruction if you want to delete an item based on its subscript. In the next example, we first delete the fourth (using subscript 3) item from the fruit list. After that, we get an error message since we tried to delete the tenth item (using subscript 9), but there were only four items in the list.

Instead of using the subscript, you can also remove an item based on a value. In this case, you use the remove() method and pass the value to remove as the argument. If the item exists more than once in the list, only the first occurrence will be deleted. If the item does not exist in the list, an error will occur, as shown in the example that follows:

The list of fruit and fruit 3 (Grape) being deleted, an error with fruit 9 (it doesn't exist), removing banana, and an error with "melon" (it doesn't exist).


Adding to a List

There are multiple ways to add items to a list. The append() method is a simple technique that just adds the required argument to the end of a list. In our next example, we use append to add the value 33 to the end of a five-item list named things.

The insert() method has two arguments, the position in the list to place the new item and the value to be inserted. In the second example, we inserted the value “tiger” at position 2, which is actually the third item in the list. When the new list is displayed, “tiger” squeezes into position 2 and all of the items after it are pushed back one slot.

A third way to add items to a list is to use the extend() method. This function is similar to the append() method except the argument to be passed is another list instead of a single data item. In the example, we created a four-item list named birds and then passed that list to the extend() method. The new contents of things include the seven items it previously stored plus the four items of the birds list.

Adding tiger to a list. Creating a list of birds, and adding it to the list "tiger" is in.


List Processing

The code below illustrates three more useful Python list methods. The first one, sort, arranges the list items in ascending order. The sort() method can also be applied on a list of strings. The reverse() method does exactly what you might guess. It just flips the order of the list. Finally, the clear() method will delete all of the items from a list. You can see from the example below that a list is empty when it displays as just two brackets [].

Examples of the different sort commands.


List Operators

Similar to the concatenation of strings, the plus (+) operator can be used to combine two lists. In the first example below, you can observe the instruction first + second is used to combine those two lists.

First + second command to combine the two lists.

In the final example, we use the multiplication (*) operator to perform repetition. Once again, this mimics the repetition functionality this operator applies with strings. Although the order does not matter, the operation requires a list and an integer. As you can see from the examples below, the list [1,2,3] is repeated five times. It is often convenient to use this repetition operator to initialize a list. For example, the final instruction initializes a 100-item list named pay to 100 values of zero.

Example of repeating lists

To conclude the chapter, we will build a full application to solve a problem:

Problem: The annual Lion Bass Fishing Tournament has hired you to write an application to help process the tournament statistics. Specifically, each team will use your application to input the weight of each fish they catch. After entering a fish weight, the program will ask the user if there are any more fish weights to enter. When the tournament concludes, the program will display summary statistics for that team. This will include a table with the weights of all fish caught, as well as the fish count, the total weight, the heaviest fish, the lightest fish, and the average weight.

On the next page, we will first model a solution to this problem with a flowchart. This is the coolest and most complex flowchart we have seen so far. Of course, it begins with the “Start” symbol and then initializes variables more and weights. You should be able to follow along with each symbol of the flowchart and then see how the flowchart naturally translates into the working Python program.

Flowchart for the Lion Bass Tournament code.
Flowchart to Model the Bass Fishing Tournament.
Python code to generate bass fishsing tournament summary.

In the program, you will notice how we took advantage of many of the list functions and methods discussed in the chapter. To add each fish to the weights list, we used the append method. To find the fish count, total weight, heaviest fish, and lightest fish, we used the lensummax, and min functions, respectively. Below, we will show the output of a sample run of the program. Notice how we used upper string method to convert all responses to more to uppercase to make our program more user friendly, so the keyboard user doesn’t need to worry about the ‘Y’ or ‘N’ input being upper or lower case.

Output of the code in the previous image.



Similar to a list, a dictionary is another Python data type that is used to store a collection of data. A a data structure that is also known as an associative array, the dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.

In the example below, a dictionary named school is created with four key-value pairs. To initialize a dictionary, you use curly brackets to enclose the data and a colon to separate each key-value pair. The example shows how to access the value of an item, as well as illustrates how to use dictionary functions and methods.

Example of dictionary using UNA information
Program illustrating a Python Dictionary.

The output when the above program is executed is seen here:

Output of the code from the previous image.
Program output.

Often times, we like to use the key as a way to access data directly. In the example below, we will create a dictionary named states that stores the population of U.S. states from the year 2000 through 2019. This data was found at a web site called Kaggle, that has thousand of freely accessible data sets that you can use for programming projects. A small chunk of this comma-separated data file is shown here:

State populations dictionary data
The populations.csv data file.

In our example, we use the state name (data[0]) as the dictionary key. The dictionary value is actually a 22-component list that consists of the state name, a state code, and then the populations for that state between 2000 and 2019. In our program, we just print the state name and the state’s 2019 population. Once this loop completes, we illustrate how you can obtain all of the data for a given state, taking the user input and using it as the dictionary key.

Python program code for reading CSV files.
Python program that reads CSV file and stores data to a dictionary.

A portion of the program output is shown below. In this example, the user entered Ohio as input and the program displayed the data for that state.

Output of the code in the previous image.
Program output.


INTERACTIVE – Python collection types

Four common data types to store collections of data in Python are illustrated in the program below. Observe the code and then run the program. Do a quick Internet search to see if you can identify the properties that differentiate these four collections.


Chapter Review Exercises:

9.1. What is the output of the following Python code?

myList = [8, 3, 14, 5, 10]

print (len(myList))

9.2. What is the output of the following Python code?

myList = [8, 3, 14, 5, 10]

print (sum(myList))

9.3. What is the output of the following Python code?

myList = [8, 3, 14, 5, 10]


print (len(myList))


Icon for the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License

Python Textbook Copyright © 2022 by Dr. Mark Terwilliger is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book