Module 3 · Arrays, Strings and Hashing · Lesson 6 of 40
Arrays and Python lists
Boxes in a row: fast to read by index, slow to insert at the front. Plus 2D lists for grids.
In this lesson · about 20 minutes
- Explain why reading by index is O(1)
- Explain why inserting at the front is O(n)
- Make and loop over a 2D list (a grid)
An array is a row of boxes, side by side in memory. Each box holds one item, and each box has a number, its index, starting at 0. In Python, the list plays the role of an array.
Why reading is fast
Because the boxes sit in a row, the computer can jump straight to box 500 without looking at boxes 0 to 499. Reading or changing nums[i] is O(1).
Why inserting at the front is slow
To put a new item at the front, every other item must slide one box to the right to make room. With n items, that is n moves: O(n). Removing from the front has the same problem. Adding or removing at the end is cheap: O(1).
| Operation | Python | Cost |
|---|---|---|
| Read / change by index | nums[i], nums[i] = 5 | O(1) |
| Add to the end | nums.append(x) | O(1) |
| Remove from the end | nums.pop() | O(1) |
| Insert or remove at the front or middle | nums.insert(0, x), nums.pop(0) | O(n) |
| Search for a value | x in nums, nums.index(x) | O(n) |
| Copy a slice | nums[2:5] | O(length of slice) |
Try it · see it work
What does each list operation cost?
Try each button. The coloured boxes show which items had to be touched or moved.
items = [7, 3, 9, 4, 6]
Pick an action to see how many steps it takes.
2D lists: grids
A list can hold other lists. That gives you a grid with rows and columns, like a spreadsheet or a game board. grid[r][c] is the item in row r, column c.
grid = [[1, 2, 3],
[4, 5, 6]]
grid[1][2] # row 1, column 2 → 6
A grid with R rows and C columns has R × C boxes, so visiting every box is O(R × C).
Try it: walk a grid
Exercise
Count the even numbers
Write count_evens(nums) that returns how many numbers in the list are even. (A number is even when n % 2 == 0.)
Exercise
Add up a grid
Write grid_sum(grid) that returns the total of every number in a 2D list.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.