Learning LibraryCore Coding LibraryKids

List indexing: grab one item by its spot

Every item in a list has a number, called its index. Use the index in square brackets to grab just that one item — like PALETTE[0] for the very first color.

The big idea

A list index picks one item by its position, and positions start counting at 0.

See it in code

1Start simple

Put the index in square brackets to grab one item. colors[0] is the first color, because lists start counting at zero. colors[1] is the second:

python
colors = ["gold", "teal", "violet"]
print(colors[0])
print(colors[1])
Run it — index 0, then index 1:
gold
teal

[0] gave the first, [1] the second. The counting starts at 0, not 1 — that's the one thing to remember.

2A step further

Keep going and the pattern holds. This list has three colors, so their indexes are 0, 1, and 2 — the last one is [2], not [3]:

python
colors = ["gold", "teal", "violet"]
print("First:", colors[0])
print("Second:", colors[1])
print("Third:", colors[2])
Run it — three items, indexes 0 to 2:
First: gold
Second: teal
Third: violet

Three items, and the last one is at [2]. Now let's use an index to color a real star.

3In our world

The art studio's PALETTE is a list of colors too. PALETTE[0] is the first color, PALETTE[1] the second — and we use each to color a star:

python
from art import Canvas, PALETTE, star

screen = Canvas.create()
Canvas.fill(screen)

print("The first color is at index 0")
star(screen, 150, 250, size=90, color=PALETTE[0])
star(screen, 350, 250, size=90, color=PALETTE[1])
Run it — two stars, colored by index 0 and index 1:
The first color is at index 0
Two large stars on a dark canvas: a rose-pink one on the left and a gold one on the right.

PALETTE[0] gave us the first color and PALETTE[1] the second — the same brackets, now picking real colors. The very first item always lives at index 0.

The same idea, everywhere

Indexing works on any list. Grab the first word in a sentence, the top score in a list of scores, or the front enemy in a wave. Whenever you want one item out of many, use its index.

Try it yourself

Change one star to PALETTE[3] and see a new color. Then try PALETTE[99] — Python will complain, because there is no item that far along the list.

The common mistake

Forgetting that counting starts at 0. The first item is [0], not [1], so in a list of 3 the last item is [2]. Reaching for [3] there goes off the end and errors.

What it unlocks

Indexing builds on lists, and pairs with for loops when you want to visit each index in turn.

Older, or want more depth? Read the Teens version →