Lists and Arrays

Lesson 3 of 20

Watch insert(2, 25) shove neighbors aside, slice a list apart, and see why b = a copies a reference instead of a list.

The big picture

The workhorse container

The list is Python’s array: ordered, mutable, indexed from 0. Master its costs and half of DSA becomes bookkeeping.

Indexing is O(1)

nums[3] jumps straight to slot 3 — the list stores its elements in one contiguous block with the length on the side.

Inserting is O(n)

nums.insert(2, 25) shifts every element from index 2 rightward. On a 10,000-element list at the front, that is 10,000 moves.

append is O(1) amortised

Python over-allocates spare slots, so appending usually touches one slot. insert(0, x) is the O(n) villain.

Slices copy

nums[1:4] builds a NEW list of three elements — the stop index is excluded, so the length is stop − start.

Assignment aliases

b = a copies the reference, not the list. Two names, one object — append through b and a sees it too. Use a.copy() to escape.