The array is the most used data structure in programming and in coding interviews. In Python, you use a list for it. You already know how to write nums.append(5), but DSA asks a different question: how much does each operation cost? Knowing that inserting at the front of a list is slow while appending at the end is fast changes which solutions you write.
This lesson explains how arrays work in memory, why Python lists are called dynamic arrays, the Big-O of every common operation, 2D lists, and a few classic array problems.
How an array works in memory
An array stores items side by side in one continuous block of memory, like a row of numbered lockers. Because every slot is the same size, the computer can jump straight to slot i with simple arithmetic: start address + i × slot size. That's why reading nums[i] takes the same time whether i is 3 or 3 million: O(1).
The downside of being side by side: inserting or deleting in the middle means shifting everything after it by one slot. Insert at the front of a list of a million items, and a million items move: O(n).
Python lists are dynamic arrays
A classic array has a fixed size. A Python list grows automatically. How? It reserves extra slots at the end. When they run out, it allocates a bigger block (roughly 1.125 times as big, plus a little) and copies everything across.
That copy is O(n), but it happens rarely, so on average append is O(1). This is called amortised O(1): an occasional expensive step spread over many cheap ones. You can watch it happen:
import sys
nums = []
last = sys.getsizeof(nums)
for i in range(20):
nums.append(i)
size = sys.getsizeof(nums)
if size != last:
print(f"length {len(nums):2}: list now uses {size} bytes")
last = size
length 1: list now uses 88 bytes
length 5: list now uses 120 bytes
length 9: list now uses 184 bytes
length 17: list now uses 248 bytes
The memory only grows at certain lengths: the list reserves room ahead of time. (Exact numbers vary by Python version.)
The cost of list operations
| Operation | Example | Big-O | Why |
|---|---|---|---|
| Read or write by index | nums[i], nums[i] = x | O(1) | Direct jump |
| Append at the end | nums.append(x) | O(1) amortised | Spare slots |
| Remove from the end | nums.pop() | O(1) | Nothing shifts |
| Insert at the front or middle | nums.insert(0, x) | O(n) | Everything after shifts |
| Remove from the front or middle | nums.pop(0), del nums[i] | O(n) | Everything after shifts |
| Search for a value | x in nums, nums.index(x) | O(n) | Checks each item |
| Remove a value | nums.remove(x) | O(n) | Search, then shift |
| Slice | nums[a:b] | O(b − a) | Copies that many items |
| Length | len(nums) | O(1) | Stored, not counted |
| Sort | nums.sort() | O(n log n) | Timsort |
| Min, max, sum | max(nums) | O(n) | Checks each item |
Two rules to remember: the end is cheap, the front is expensive, and searching is O(n). If you need fast work at both ends, use collections.deque. If you need fast searching, use a set or dictionary, covered in hash maps for coding problems.
A hidden O(n²) trap
This looks innocent:
def remove_negatives_slow(nums):
for x in list(nums):
if x < 0:
nums.remove(x) # O(n) each time
return nums
Each remove searches and shifts, O(n), inside a loop of n items: O(n²) overall. Building a new list is O(n):
def remove_negatives(nums):
return [x for x in nums if x >= 0]
print(remove_negatives([3, -1, 4, -5, 9])) # [3, 4, 9]
Two-dimensional lists
A grid is a list of lists, where grid[row][col] reads one cell. Create one with a comprehension:
rows, cols = 3, 4
grid = [[0] * cols for _ in range(rows)]
grid[1][2] = 7
for row in grid:
print(row)
[0, 0, 0, 0]
[0, 0, 7, 0]
[0, 0, 0, 0]
Never write [[0] * cols] * rows. It makes 3 references to the same inner list, so changing one row changes all of them:
bad = [[0] * 4] * 3
bad[1][2] = 7
print(bad) # [[0, 0, 7, 0], [0, 0, 7, 0], [0, 0, 7, 0]]
Loop through a grid with nested loops over range(rows) and range(cols): O(rows × cols).
In-place operations
"In place" means changing the input list without making a new one, using O(1) extra space. Interviewers often ask for it. Reversing a list by swapping from both ends:
def reverse_in_place(nums):
left, right = 0, len(nums) - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
a = [1, 2, 3, 4, 5]
reverse_in_place(a)
print(a) # [5, 4, 3, 2, 1]
This uses the two pointers pattern, which has its own lesson: the two pointers technique.
Classic problem: rotate an array
Rotate a list to the right by k steps: [1, 2, 3, 4, 5] rotated by 2 becomes [4, 5, 1, 2, 3].
The Python way uses slicing, O(n) time and O(n) space:
def rotate(nums, k):
k %= len(nums) # rotating by len(nums) changes nothing
return nums[-k:] + nums[:-k]
print(rotate([1, 2, 3, 4, 5], 2)) # [4, 5, 1, 2, 3]
The k %= len(nums) line handles an edge case: rotating 5 items by 7 is the same as rotating by 2. Interviewers love that detail.
Classic problem: move zeros to the end
Move all zeros to the end, keeping the order of the others, in place:
def move_zeros(nums):
write = 0
for x in nums:
if x != 0:
nums[write] = x
write += 1
for i in range(write, len(nums)):
nums[i] = 0
a = [0, 1, 0, 3, 12]
move_zeros(a)
print(a) # [1, 3, 12, 0, 0]
write marks where the next non-zero belongs. One pass, O(n) time, O(1) space.
Practice
- Find the second largest distinct number in a list in one pass.
Show the answer
def second_largest(nums):
first = second = float("-inf")
for x in nums:
if x > first:
first, second = x, first
elif first > x > second:
second = x
return second if second != float("-inf") else None
print(second_largest([4, 9, 2, 9, 7])) # 7
O(n) time, O(1) space. Sorting would be O(n log n).
- Why is
nums.pop(0)in a loop slow, and what should you use instead?
Show the answer
Each pop(0) shifts every remaining item left, O(n), so a loop is O(n²). Use collections.deque and popleft(), which is O(1), or iterate with an index.
- Write a function that returns the running maximum:
[3, 1, 4, 1, 5]gives[3, 3, 4, 4, 5].
Show the answer
def running_max(nums):
result, best = [], float("-inf")
for x in nums:
best = max(best, x)
result.append(best)
return result
Interview questions
Why is accessing an array element O(1)?
Elements are stored contiguously and are the same size, so the address of element i is computed directly as base + i × size, with no searching.
What is a dynamic array and why is append amortised O(1)?
An array that resizes itself by allocating a larger block and copying when full. Copying is O(n) but happens geometrically rarely, so the total cost of n appends is O(n), averaging O(1) each.
Why is inserting at the beginning of a list O(n)?
Every existing element must shift one position to make room, so the work is proportional to the length.
What to learn next
- Make searching O(1) with hash maps for coding problems.
- Review the costs in Big-O notation in Python.