Learning LibraryCore Coding LibraryKids

Lists: keep many things in one place

A list is one box that holds many things, kept in order. You can add to it, loop over it, and grab any item by its spot.

The big idea

A list holds many values in order. You can loop over them or pick one by its position.

See it in code

1Start simple

A list is just things inside [ ], kept in order. Here are three color names in one box called colors. len(colors) counts how many are in it:

python
colors = ["gold", "teal", "violet"]
print("My colors:", colors)
print("How many:", len(colors))
Run it — one box, three things inside:
My colors: ['gold', 'teal', 'violet']
How many: 3

One name, colors, holds all three. len counted them for you: 3.

2A step further

The magic of a list is looping over it. A for loop visits each item in turn, so you write the step once:

python
colors = ["gold", "teal", "violet"]
for c in colors:
    print("Draw a", c, "star")
Run it — one line, once for every color:
Draw a gold star
Draw a teal star
Draw a violet star

The loop ran three times, once per color. Now let's make each trip draw a real star.

3In our world

The art studio's PALETTE is a list too. We pick three of its colors into a list called colors, then loop over the list and draw a star in each color:

python
from art import Canvas, PALETTE, star

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

colors = [PALETTE[1], PALETTE[2], PALETTE[4]]
print("Colors in my list:", len(colors))

for i in range(len(colors)):
    star(screen, 130 + i * 120, 250, size=80, color=colors[i])
Run it — three colors in the list, three stars on the canvas:
Colors in my list: 3
Three stars in a row on a dark canvas: one gold, one teal, one violet.

Same loop as before, but now each color paints a star. Add a fourth color and a fourth star will appear — the list just grows.

The same idea, everywhere

Lists are everywhere. A wave of enemies, a row of high scores, the lines of a story, the bases in a strand of DNA — each one is a list. Store many things under one name. Then loop over them all.

Try it yourself

Add PALETTE[5] to the end of the colors list, then run again — a fourth star appears, and you never touched the loop.

The common mistake

Counting from one. The first item in a list is at position 0, not 1. So colors[0] is the first color and colors[1] is the second.

What it unlocks

Lists open up list indexing to grab one item, list methods to add and remove, and for loops to visit every item in turn.

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