Repeating and Remembering

Lists: Remembering Several Values


Learning Objectives

  • You can create a list and access its items by index.
  • You can use len(...) and in with lists.
  • You can change an existing list item and append new items.
  • You can use a direct for loop to process the values in a list.
  • You understand an important difference between strings and lists: lists can be changed in place.

A string gives you a sequence of characters, but programs need many other kinds of collections. A course may have several scores. A weather program may have several temperatures. A reading log may contain several book titles.

Python lists let you store several values in one collection.

Creating a List

A list is written using square brackets:

scores = [12, 8, 15, 10]

The list contains four integer values.

Lists can also contain strings:

languages = ["Python", "JavaScript", "Rust"]

An empty list contains no items:

values = []

As with strings, the items in a list have positions.

Indexing Lists

Indexing works just as it did for strings:

scores = [12, 8, 15, 10]
print(scores[0])
print(scores[2])

The output is:

12
15

The first index is 0, and len(...) gives the number of items:

print(len(scores))

prints 4.

The last non-negative index is therefore 3.

Negative indexes work as well:

print(scores[-1])

prints the final value, 10.

The next starter reads four city names into variables. Put those values into a list using square brackets. Print the complete list, then read its first and last items and find its length. Adding items to an existing list is introduced later in this chapter.

Build and inspect a city list

0 / 10 points

The starter reads four city names, one per line, without visible prompts. Put the four stored values into a list called cities, in input order. Create the list using square brackets, as in the chapter’s examples.

Print the complete list, then use it to print its first item, last item, and length. For these inputs:

Helsinki
Oslo
Tallinn
Reykjavik

the output must be:

Cities: ['Helsinki', 'Oslo', 'Tallinn', 'Reykjavik']
First: Helsinki
Last: Reykjavik
Number of cities: 4

You can print the complete list with print(f"Cities: {cities}"). Python displays square brackets around the list and quote marks around its string items.

Your program must work with other city names too. Preserve each name as entered, including spaces within names. Two cities may have the same name.

Membership Works with Lists Too

The in operator tests whether a list contains a particular value:

countries = ["Finland", "Norway", "Estonia"]
print("Norway" in countries)
print("Sweden" in countries)

The output is:

True
False

Notice what is being compared. With a list of countries, Python looks for a complete list item. The expression "Finland" in countries asks whether one of the items equals "Finland". A fragment such as "land" is not itself a list item, even though those letters occur inside "Finland".

Lists Can Change

Here is an important difference from strings. You can replace an item in a list:

No files opened Select a file to edit

The output is:

[12, 10, 15]

The list itself has changed.

Trying the corresponding operation with a string does not work:

word = "cat"
word[0] = "b"

Python reports an error. Strings are immutable: their characters cannot be replaced in place. Lists are mutable: their items can be changed.

You do not need a detailed theory of mutability yet. For this part, remember the practical distinction:

You can read items from both strings and lists, but you can replace items in a list.

Correct the color list

0 / 10 points

The starter reads three color names into a list called colors. It then reads a replacement color. Each value is entered on its own line without a visible prompt.

Replace the middle item by assigning to its index, then print the complete list. Keep the first and last items unchanged, even if they have the same name as the middle item.

For these inputs:

red
green
blue
yellow

the output must be:

['red', 'yellow', 'blue']

Your program must work with other color names and replacement values. Preserve the names as entered. A name may contain spaces, and the replacement may be the same as the current middle item.

Adding Items with .append(...)

Lists can also grow:

books = []
books.append("Frankenstein")
books.append("The Odyssey")
print(books)

The output is:

['Frankenstein', 'The Odyssey']

When Python displays a complete list, it uses square brackets around the list, commas between its items, and quote marks around items that are strings. Python may display single quotes even if you used double quotes when creating the strings. These quote marks show where each string item begins and ends; they are not part of the book titles themselves.

For example, printing one item displays only the text stored in that string:

print(books[0])

The output is:

Frankenstein

.append(...) changes the existing list by adding one item at the end.

Write:

books.append("Frankenstein")

Do not write:

books = books.append("Frankenstein")

The purpose of .append(...) here is to modify books, not to produce a new updated list that you assign back.

Collect three tasks

0 / 10 points

Start with an empty list named tasks. Read three task names, one per input line and without visible prompts.

Use one for loop over range(3). On each iteration, read one task and append it to tasks. After the loop, print the completed list in this form:

Tasks: ['Read', 'Code', 'Rest']

The example assumes the three input lines are Read, Code, and Rest. Your program must work with other task names as well.

for Works with Lists

You already know how for works. Lists simply provide another kind of sequence:

scores = [12, 8, 15, 10]
for score in scores:
print(score)

Compare the two loops:

for character in word:
print(character)
for score in scores:
print(score)

Whether the sequence contains characters, scores, or city names, each iteration gives the loop variable the next item and runs the body.

Print selected temperatures

0 / 10 points

The starter reads a non-negative number of temperatures, then that many whole-number temperatures, one per line. It stores the temperatures in a list. The input code is already complete.

Use a direct for loop to print only the temperatures that are at least 20, one per line. Preserve their order and repetitions. A temperature of exactly 20 must be included.

For these inputs:

5
18
21
17
23
20

the output must be:

21
23
20

Print nothing if the list is empty or no temperature meets the condition. Use the values in the list so the program also works for other temperatures and list lengths.

Explain Changes in Execution Order

Step through the program below. Before clicking Next, predict which part of the list or program state will change. Notice that appending creates a new position, while assignment replaces the value at an existing position. The loop then visits the changed list.

Code

Step 1 of 10

1 / 10
Formatting...

State

main

No variables

Objects

No objects yet

Output

No output yet

In the next exercise, explain what happens to the list and what the program prints, following the statements in execution order.

Explain a list program

0 / 10 points

Explain in plain language what happens in this program:

colors = ["red", "blue"]
colors.append("green")
colors[0] = "gold"
for color in colors:
print(color)

In three or four sentences, explain how the list changes in execution order and what the loop prints. Distinguish adding a new item from replacing an existing item.

Strings and Lists

At this point, the similarities and differences are useful to collect in one place:

Operation or propertyStringList
ordered sequenceyesyes
indexingyesyes
len(...)yesyes
membership with inyesyes
direct for loopyesyes
item can be replacednoyes
can grow with .append(...)noyes

You will build on this comparison throughout the course. Later, other kinds of collections will have their own strengths and limitations.

Empty Lists

An empty list behaves naturally with a for loop:

values = []
for value in values:
print(value)
print("Finished")

The loop body runs zero times.

This is often useful: an algorithm can process a list whether it has zero, one, or many items. However, operations such as values[0] still require at least one item. Pay attention to that distinction in the next chapter.

Check Your Understanding

  1. How are list indexes similar to string indexes?
  2. What does .append(...) change?
  3. What is the practical difference between a mutable list and an immutable string?
  4. In for score in scores:, what value does score receive on each iteration?
  5. When Python displays a list of strings, are the quote marks part of the stored text?

AI Study Aid

Create a chapter diagram

We're looking into to what extent AI-generated diagrams could help with studying.

Use this study aid to generate an AI-generated visual summary of the material you just studied. Each diagram style emphasizes the content in a different way, so you can choose the focus that feels most useful.

Using the diagram generator is voluntary and does not affect your course progress. We encourage you to try it out and see if it helps, but it's totally up to you! Your answers help us understand how to make better study aids in the future.

Diagrams tried: 0