We met arrays in Episode 2. Now we can explain why they are fast: their items live in an ordered row, so an index acts like a direct address.
Indexes are the array's superpower
Reading or replacing one item by index is O(1). The computer can calculate where that item lives without walking through earlier items.
- Read by index: O(1).
- Search an unsorted array: O(n).
- Append to a dynamic array: usually O(1).
- Insert near the beginning: O(n) because items must move.
Moving items changes the cost
If we insert a new first item, every existing item shifts one position. Arrays are excellent for indexed reading but not always ideal for frequent changes at the front.
scores = [12, 18, 15, 20]
print(scores[2]) # 15
scores[2] = 17 # direct replacement
scores.append(22) # efficient at the end
scores.insert(0, 9)
print(scores)Choosing a data structure means matching its strengths to the operations your problem performs most often.
Your tiny challenge
For a music playlist, list the operations you expect: reading song 20, adding at the end, or inserting at the beginning. Which ones fit an array best?
