Chapter 8

Lists: Working with Many Values

One variable can hold a whole ordered collection of values, and that collection can change.

Chapter 8, Lists: Working with Many Values

What you will learn

  • Create, index, slice, and modify lists.
  • Use append(), insert(), remove(), and pop().
  • Loop through lists and compute totals.
  • Understand aliasing and copying at a beginner level.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

8.1 Create and Read a List

TPRM Lab 8.1: Indexes Start at Zero

Type this into a file, predict the output, then run it.

Python
fruits = ["apple", "banana", "cherry", "date"]

print(fruits[0])
print(fruits[-1])
print(len(fruits))
print(fruits[1:3])

8.2 Lists Are Mutable

TPRM Lab 8.2: Change a List In Place

Type this into a file, predict the output, then run it.

Python
scores = [70, 85, 92, 60]
print("Before:", scores)

scores[0] = 75
scores.append(88)
scores.remove(60)

print("After:", scores)

8.3 Processing a List

Type this into a file, predict the output, then run it.

Python
scores = [70, 85, 92, 60, 78]
total = 0

for score in scores:
    total += score

average = total / len(scores)
print(average)

8.4 The Aliasing Surprise

Type this into a file, predict the output, then run it.

Python
a = [1, 2, 3]
b = a
b.append(4)
print(a)

Back to Python the TPRM Way