Lists

Overview

Teaching: 10 min
Exercises: 10 min
Questions
  • How can I store multiple values?

Objectives
  • Explain why programs need collections of values.

  • Write programs that create flat lists, index them, and modify them through assignment and method calls.

We have been working with one dataset at a time. With programming however, we have the ability to reproduce the same work on multiple sets of data. Let’s look at some concepts that will allow us to later group together a collection of file names for us to repeat analysis on.

A list stores many values in a single structure.

pressures = [0.273, 0.275, 0.277, 0.275, 0.276]
print('pressures:', pressures)
print('length:', len(pressures))
pressures: [0.273, 0.275, 0.277, 0.275, 0.276]
length: 5

Use an item’s index to fetch it from a list.

print('first item:', pressures[0])
print('fifth item:', pressures[4])
print('last item:', pressures[-1])
zeroth item: 0.273
fourth item: 0.276
last item: 0.276

Indexing beyond the end of the collection is an error.

print('100th item:', pressures[99])
IndexError: string index out of range

Lists’ values can be replaced by assigning to them.

pressures[0] = 0.265
print('pressures is now:', pressures)
pressures is now: [0.265, 0.275, 0.277, 0.275, 0.276]

Appending items to a list lengthens it.

pressures.append(0.269)
print('pressures:', pressures)
pressures: [0.265, 0.275, 0.277, 0.275, 0.276, 0.269]

Key Points

  • A list stores many values in a single structure.

  • Use an item’s index to fetch it from a list.

  • Lists’ values can be replaced by assigning to them.

  • Appending items to a list lengthens it.

  • Indexing beyond the end of the collection is an error.