A row of boxes
An array stores items side by side in memory, in numbered slots. A Python list is an array under the hood.
Think of it like this: A row of numbered seats in a cinema. To find seat 57 you walk straight to it – you don't need to check seats 1 to 56 first. That's why
items[57]is instant.
What's fast and what's slow
| Operation | Python | Big-O | Why |
|---|---|---|---|
| read / change by index | a[i], a[i] = x | O(1) | jump straight to the slot |
| add at the end | a.append(x) | O(1)* | the next slot is free |
| remove from the end | a.pop() | O(1) | nothing else moves |
| insert / remove at the front | a.insert(0, x), a.pop(0) | O(n) | every other item shifts one slot |
| search for a value | x in a | O(n) | may have to check every item |
| length | len(a) | O(1) | Python stores it |
*Usually. Now and then Python moves the list to a bigger block of memory, but on average it's still O(1).
Seeing the shift
seats = ["A", "B", "C", "D"]
seats.insert(0, "Z") # Z goes in front: A, B, C, D all shift right
print(seats)
seats.pop(0) # Z leaves: everyone shifts back left
print(seats)Output
['Z', 'A', 'B', 'C', 'D'] ['A', 'B', 'C', 'D']
Think of it like this: If someone pushes into the front of a queue, every single person behind has to take a step back.
Walking through an array
temps = [31, 29, 35, 33, 28]
hottest_day = 0
for day in range(len(temps)):
if temps[day] > temps[hottest_day]:
hottest_day = day
print("Hottest was day", hottest_day, "at", temps[hottest_day])Output
Hottest was day 2 at 35
Tip: If your program does lots of
insert(0, x)orpop(0), that's a sign you want a different data structure – likecollections.deque(Module 10).