An array is like a row of boxes. Every box can hold one thing, and every box has a position.

Programmers use arrays when they want to keep a group of related things together: scores, names, colors, prices, or steps in a game.

The first box is box zero

Computers often start counting at zero. In the array red, blue, green, the color red is at position 0, blue is at position 1, and green is at position 2. A position is also called an index.

If we ask for position 1, the computer can jump straight to blue. It does not need to open every box first. That makes reading one array item very fast.

Things we can do with an array

  • Read a box by its index.
  • Change what is inside a box.
  • Walk through every box from left to right.
  • Add a new box, if there is room.
  • Remove a box and move the others closer.

Suppose our snack array is apple, banana, cookie. If the banana is gone, we can put orange in box 1. The row becomes apple, orange, cookie.

Open and change an array boxPython
snacks = ["apple", "banana", "cookie"]

print(snacks[1])  # banana
snacks[1] = "orange"

print(snacks)  # ['apple', 'orange', 'cookie']

When arrays feel easy

Arrays are great when order matters and we often ask for an item by position. A week of temperatures fits nicely because Monday can be in one box, Tuesday in the next, and so on.

Adding something in the middle can be slower. If a new child joins the middle of a line, everyone after that child may need to move one step.

Your tiny challenge

Make an array with five favorite foods. Point to the food at index 0, then index 3. Replace one food. You now understand the heart of an array: one tidy row, with an address for every box.