Chapter 6, Lesson 1 Text

Chapter Six: Lists and Loops

Lesson One: Lists and Tuples


The numeric, string and other variables that you have used so far can only hold a single data value. However, your Python program may need to keep track of many data values. For example, how would you store 10 high game scores? You might declare variables like highScore1highScore2highScore3 and so on, but that many variables will be hard to manage. Imagine the amount of code you would need to write to track 100 or 1000 data values!

Clearly, we need a better way to manage large data sets. Fortunately, Python allows us to store as many values as we need in a single list. list is a type of variable that holds zero, one or more data values.

Creating Lists in Python

Lists are stored in variables that you name and initialize similar to numeric and string variables. But, instead of a single value to the right of an assignment statement, you can store multiple values. Each value should be separated by a comma and the entire list must be surrounded by opening and closing square brackets [ and ].

The example below declares a list variable named highScores and initializes it with 10 different values.

highScores = [1000, 950, 875, 600, 550, 500, 443, 410, 395, 380]

You can create lists of any type of data.

prices = [9.99, 10.25, 19.99, 100.0]
dogBreeds = ["Poodle","Collie","Terrier", "Beagle"]
logicalResults [True, True, False, True]

You can even mix different kinds of data in the same list!

myCollection = [1000, 3.14159, "Carrots", False]

Printing List Contents

The print() function understands lists, and you can print out the contents of a list simply by passing in the list variable name. In fact, anywhere that you would normally pass a string value into a print() function as a parameter, you can substitute a list instead. Try running the code below to see the contents of each sample list.

Try It Now

Notice that you cannot simply add a list and a string together with the plus sign (+). A list and a string are two different data types, and you will get an error if you try to add them together directly. Try un-commenting the last line and re-running the example to see this run-time error.

When printing, be sure you pass the list into a function that knows how to convert it to a string. The str.format() function also knows how to convert lists to strings, as you can see in the above example. We pass in the myCollection list as a str.format() parameter, and the contents are converted to a string and placed at the first placeholder brackets {} in the output text.

Getting and Setting Individual List Elements

You can get and set each item in a list individually, when needed. Every list element is assigned a numeric valuecalled an index. Index values are integers that start at 0 for the left-most item and go up by 1 for each item to the right. So, if a list has 10 elements, the index values for the data elements will range from 0 through 9. The illustration below shows how each data element in our sample highScores list has an index value from 0 through 9.

Example index values from 0 through 9 for highScores list

To access a specific item within a list, use the variable name plus item's index value in square brackets. The example below uses our highScores example list. It reads the first item out of the list using highScores[0] and the last item using highScores[0], then prints each value to the screen.

Try It Now

Similarly, you can set a new value at any position with an assignment statement. Just use the variable name and index in square brackets on the left side of the equals sign. Try running the example below, where we update the first three elements of a list using highScores[0]highScores[1] and highScores[2] in assignment statements.

Try It Now


Always remember the first index value is 0 and the last index value is one less than the number of items in the list. If you try to use any other index value, you will get a run-time exception! If you try to set highScores[10] in the example above, you will receive a run-time exception on that line that says "list assignment index out of range". Try it and see!


Using Ranges

Writing a single index value in brackets, like highScores[0], will refer to a single item in a list. You can access a range of items by writing a starting and ending index, separated by a colon, like highScores[1:4]. The range will start at the first index and run up to, but not including the last index. Therefore, a range of [1:4] will get the elements at index 1, 2 and 3.

Try It Now

This will only work to read groups of elements. You cannot do a mass-update of multiple list elements using ranges!

highScores = [1000, 950, 875, 600, 550, 500, 443, 410, 395, 380]
highScores[1:4] = 0   # ERROR - cannot assign value to a range of elements



You may occasionally want to create a list of items that cannot be changed. For example, you might declare a list of categories for a "cat" competition as follows:

categories = ["Laziest", "Snootiest", "Most Playful", "Most Likely to Yack in Your Shoe"]  # a list

Now, you really don't want those categories to ever change; they should remain constant. However, there is nothing to keep some later code from changing those categories accidentally (or on purpose).

categories = ["Laziest", "Snootiest", "Most Playful", "Most Likely to Yack in Your Shoe"]
categories[0] = "Meanest"   # This will work

To create a set of values that is constant and cannot be changed, you can use a tuple instead of a list. A tuple, beyond the funny name, is just basically a list where none of the assignment or update functions will work. To create a tuple, use parentheses ( and ) around the initial set of values, like this:

categories = ("Laziest", "Snootiest", "Most Playful", "Most Likely to Yack in Your Shoe")  # a tuple

Now, you can print a tuple and read values out of a tuple, just like a list. Use the same square brackets when providing index values or ranges. The example below creates a tuple and prints the whole list, a specific element and a range of elements.

Try It Now

The last line attempts to assign a new value to a tuple element. If you un-comment that line and re-run the code, you will see the run-time exception on that invalid operation: 'tuple' object does not support item assignment.

Lists vs. Tuples - Which to Use?

The biggest difference between a list and a tuple is that you can change a list after it is created. List items can be changed and individual list items can be added or removed. However, a tuple has a fixed set of items that cannot be changed. In programming terminology, tuples are "immutable", which is just a fancy way of saying you can't change them.

Both lists and tuples can hold all kinds of data, including integers, strings, Boolean values or mixtures of those data types. You can even store other lists and tuples inside individual data elements! Your biggest technical decision when selecting a list or tuple is whether or not you want to keep the data constant after you initialize it. If the data needs to be kept constant, use a tuple, otherwise use a list.

For simplicity, we will generally use lists in our course examples, unless we are specifically exploring tuples or have a good technical reason to use tuples.


Work with Me: Hobby List


Using the code window below, practice working with lists on your own.

  1. Create a list called myHobbies to hold your favorite hobbies. Initialize it with at least 3 activities that you like to do. Each activity can be a simple string like "Swimming".
  2. Then, print the myHobbies list to verify the contents.
  3. Next, print out the second item in the list.
  4. Next, replace the third item in the list with "guitar" or another activity name.
  5. Next, print out the updated list and verify the contents.
  6. Finally, print out just the first and second items using a range.

Try It Now



The example below demonstrates the kind of output you should expect to see. Of course, the specific activities will be your own!

['reading', 'video games', 'horse riding', 'mountain biking']
video games
['reading', 'video games', 'guitar', 'mountain biking']
['reading', 'video games']

End of Lesson

Last modified: Wednesday, 8 May 2019, 8:55 AM