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 highScore1, highScore2, highScore3, 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!

Data Abstraction
Clearly we need a better way to manage large data sets, which brings us to the concept of data abstraction. We talked about abstraction in general terms in a previous lesson. But what is "data" abstraction? Data abstraction allows us to simplify large sets of data by giving the entire set a single variable name. This variable name can then represent the entire set of data without getting bogged down in the details of each item in the set's data type. This simplification can really make a program easier to develop and maintain.

Most programming languages support this type of data abstraction with a special data type that allows you to organize similar pieces of data into specific groups. The Python language supports data abstraction through the use of the list, which will allow us to store as many values as we need in a single variable name. A list is a type of variable that holds zero, one, or more data values.

In Python, a list can hold a mixture of data types like integers, floating-point values, and strings. In other languages, a list or "array" might require that all values in one data set have the same data type.
To see the true power of data abstraction and lists, let's back up and imagine a program where we would need to save the high score values for the top five players. In this example, you would not be able to store all five values in a single variable. Instead, you would need to use (and keep track of) five numeric variables.

Try It Now

This may not seem terrible but now think about saving the scores of the top ten players, or the top twenty players. How many lines of code would you need? How difficult would it be to keep track of all of those variables? Clearly we need a better method that simplifies our program and uses less code.

This is where the power of a Python list can be seen. Using a list in this program will allow us to easily store multiple scores. Lists are great at doing exactly this sort of work in your program.

Creating Lists in Python
Lists are stored in variables that you name and initialize like 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 ].

To declare an empty list variable named highScores with no initial values, simply set the variable equal to an empty set of square brackets [].

highScores = []
Copy
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]
Copy
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]
Copy
You can even mix different kinds of data in the same list!

myCollection = [1000, 3.14159, "Carrots", False]
Copy
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 value called 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 the 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[9], 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 indexes 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
Copy
Tuples
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
Copy
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
Copy
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
Copy
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.

1. Which of the following successfully declares a list named "marbles" and initializes the contents to the string values "red", "green" and "blue"?
Select one:

a.
marbles = list.create("red", "green", "blue")

b.
marbles = ["red", "green", "blue"]

c.
marbles = [red, green, blue]

d.
marbles = ("red" : "green" : "blue")

2. Which type of data can be stored in a list?
Select one:

a.
All of these can be stored in a list

b.
Integer

c.
String

d.
Boolean

3. What is the output of the following code?
count = 0
hobby = "marbles"
for letter in hobby:
count = count + 1
print(str(count))
Select one:

a.
0

b.
7

c.
5

d.
6

4. What is the output of the following code?
hobby = "marbles"
for letter in hobby:
print("#" + letter,end="")
Select one:

a.
#m#a#r#b#l#e#s

b.
Syntax error; you cannot iterate over the letters in a string using a "for" loop

c.
marbles

d.
#######

5. Which of the following "for" loops will successfully iterate with an index variable that ranges from 0 up through (and including) 4?
Select one:
a.
for i in [0,5]

b.
for i in range(0,5):

c.
for i range(1,4):

d.
for i in range(0:4):

a. for i in [0,5]

Answer to 1-5

1. b. marbles = ["red", "green", "blue"]

2. a. All of these can be stored in a list
3. c. 7
4. a. #m#a#r#b#l#e#s
5. b. for i in range(0,5):