Computer science
Lists
Store many values neatly in a row and find them again precisely.
What you need first
Your playlist, your shopping list, the standings of your favourite league: in all of them, many things sit in a fixed order. Programs use lists for exactly that. Instead of creating 100 separate variables for 100 songs, you put them all into one list and access any single one of them directly.
Many values, one order
A list is like a shelf with numbered slots. Each slot holds one value, and the order is preserved: what you put in first stays at the front. The number of a slot is called its index. With the index you tell the program exactly which element you mean, for example: give me the element at index 2. In many programming languages such a row of slots is called an array, and it is the same principle.
Counting starts at 0.
Counting starts at 0
Now comes the most important rule, and it causes one of the most common bugs in all of programming: the index starts at 0, not at 1. The first element has index 0, the second index 1, and so on. In the list [7, 2, 9], the 7 sits at index 0 and the 9 at index 2. The last element of a list with 5 elements therefore has index 4, not 5.
Length and changing
The length of a list is the number of its elements: [3, 1, 4] has length 3. Because counting starts at 0, the last index is always length minus 1. Using the index you can also replace an element: if in [2, 4, 6] you set the element at index 1 to 5, the list becomes [2, 5, 6]. All the other slots stay unchanged.
Exercises
0 of 6 solvedTime to try it yourself. You can't break anything, every attempt counts.
Given the list [4, 8, 15]. Which element is at index 0?
Given the list [7, 2, 9, 5]. Which element is at index 2?
How long is the list [3, 1, 4, 1, 5]?
In the list [7, 2, 9], the 9 is at index ….
A list has 6 elements. What is the index of the last element?
Match each position in the list to its index.
Where this leads