Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

Many values, one name

So far each box has held one value. But what if you have thirty marks, or a whole week of days? Thirty boxes with thirty names would be a mess.

A list is one name for a row of boxes, numbered from 0. You write it with square brackets, with the values separated by commas. Position 0 holds the first value, position 1 the second, and so on. Some languages call a list an array. It is the same idea, and you'll meet it again in the Arrays course.

A list: is one name for a row of numbered boxes.
In code
names = ["Mon", "Tue", "Wed"]
first = names[0]       # "Mon"
how_many = len(names)  # 3

A list as a lookup table

A list can work like the table in a phone book: you give it a position and it gives you what is stored there. To turn a day number into a name, store the names in order, and use the number to look one up.

But there is a catch. People count days from 1: Monday is day 1. The list counts from 0: Monday is at position 0. So the day number minus 1 is the position. Forgetting the minus 1 is the most common slip with lists.

People start counting at 1, lists start at 0. Subtract one.
Looking up day number 3
Mon
0
Tue
1
Wed
2
Thu
3
Fri
4
Sat
5
Sun
6
position
n
3

The names sit in the list in order. Monday is at position 0.

Move 1 of 3