1. The problem
One box holds one thing. You rarely have just one thing, though. You have a shopping list, a row of photos, the scores of a game. You need to keep many values together and still find any one of them fast.
2. A row of numbered boxes
A list (also called an array) is a row of boxes that stand side by side, in order. Each box has a position number, so you can point at exactly one of them. The position number is also called an index.
One thing surprises beginners: positions start at 0, not 1. The first box is at position 0, the second at position 1, and so on. It feels odd at first. After a day or two you get used to it.
3. Reading by position
You point at a box by its number. list[0] is the first value (7 in the picture above). list[2] is the third value (9). The square brackets mean "the box at this position." Every box has a number, so the computer opens the right one straight away and doesn't look through the others on the way.
4. Your turn (no code)
Take the row from the picture: [7, 3, 9, 2, 6].
- What is
list[1]? Answer: 3 (the second box). - What is
list[4]? Answer: 6 (the fifth and last box). - How many boxes are there, and what is the position of the last one? Answer: 5 boxes, and the last position is 4. The last position is always one less than the number of boxes. Getting this "one less" wrong causes a huge number of real bugs.
5. Takeaway
A list is many values in a numbered row. You reach any of them by its position. Counting starts at 0, so the last position is one less than the length of the list. Almost everything ahead (searching for a value, sorting, and much more) is a different way of walking through these boxes.
On LeetCode
No LeetCode problem yet, since this lesson writes no code. Almost every easy LeetCode problem hands you an array, and reading it by position from 0 is what lessons 7 and 10 build on.
Reading as a guest
Every free lesson is open to read and run. A free account marks lessons done and shows where you are in the course.