Indexing and Slicing

Indexing reads one item from an ordered collection.

Output:

8

Python starts indexing at 0. The first item is index 0, not index 1.

Positive Indexes

For:

scores = [8, 6, 9]

the indexes are:

IndexValue
08
16
29

This connects directly to earlier off-by-one errors.

Negative Indexes

Negative indexes count from the end:

Output:

9

-1 means the last item.

Slices

A slice reads part of a sequence:

Output:

[6, 9]

The start index is included. The stop index is excluded.

Index and slice

The slice includes index 1 and stops before index 3.

Runs locally with Python in your browser.

Ready to run.

Strings Can Be Indexed Too

Strings are ordered sequences of characters:

Output:

t
oke

This will matter later when text becomes data.

Indexing Starts at Zero

This fails:

There are three items, but the last index is 2.

Exercise: Read an index

What does this print?

Answer it first, then check.

HintCount from zero

Label the items with indexes 0, 1, and 2 from left to right.

SolutionIndex one selects B

"A" is at index 0, "B" is at index 1, and "C" is at index 2. The program prints B.

Slices Select a Range Without the Stop Index

Indexing and slicing are boundary work. Always ask which endpoint is included and which endpoint is excluded.