Lists & Slicing
Master Python dynamic arrays, zero-based and negative indexing, the mechanics of slice copies, and the crucial distinction between shallow and deep copies.
Dynamic Arrays of Object Pointers
In Python, a list is an ordered, mutable sequence of arbitrary objects. Under the hood in CPython, a list is implemented as a dynamic array of pointers (PyObject*), not a linked list.
Because the pointers are stored contiguously in memory, accessing any element by its numeric index with items[i] is a lightning-fast O(1) constant-time operation.
Lists can store mixed data types simultaneously, including integers, strings, floats, and even other nested lists.
Dual-Direction Indexing & Slice Notation
Python provides dual indexing for every sequence. Positive indices count forward from left to right starting at 0. Negative indices count backward from right to left starting at -1 (where -1 always references the final element).
Slice notation sequence[start:stop:step] extracts a subsequence. The start index is inclusive, but the stop index is exclusive: items[1:4] extracts indices 1, 2, and 3.
Omitting indices falls back to sensible defaults: start defaults to 0, stop defaults to len(items), and step defaults to 1.
Slicing Tricks and Common Methods
A negative step reverses the iteration direction: items[::-1] returns a reversed copy of the entire list in a single memory-efficient C-level operation.
Adding elements: items.append(x) adds an element to the end in amortized O(1) time. items.extend(iterable) unpacks and appends each element from another iterable.
Removing elements: items.pop() removes and returns the last element in O(1) time. In contrast, items.pop(0) or items.insert(0, x) requires shifting every remaining pointer in memory, costing O(n) linear time.
The Slicing & Memory Inspector
Test different slicing expressions on an array. Watch how positive and negative indices align, and inspect the resulting shallow-copied subarray in memory.
Python Rule: Slicing (items[start:stop]) always constructs a brand new list in heap memory. Modifying the outer slice never alters the original outer list.
Slice from index 1 up to (excluding) 4. Stop index 4 is omitted.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Python lists are contiguous dynamic pointer arrays, offering O(1) random access indexing.
- Positive indices count from 0 (left to right); negative indices count from -1 (right to left).
- Slicing [start:stop:step] is half-open: start is inclusive, stop is strictly exclusive.
- Slicing creates a shallow copy: outer arrays differ, but nested mutable objects remain shared.
- Avoid pop(0) on large lists; use collections.deque for O(1) FIFO queues.
Done with this concept?
Mark it complete to track your progress. No login needed.