List (Dynamic Array)#
Python's list is a dynamic array: contiguous storage that grows automatically. It is the default sequential container for most interview problems.
When to use a list#
| Use list | Consider alternative |
|---|---|
| Index by position O(1) | Linked list if middle insert/delete dominates (rare in Python) |
| Stack (append/pop end) | Same — list is fine |
| Queue | collections.deque — never pop(0) |
| Sorted collection | bisect on list, or BST/heap depending on ops |
Complexity#
| Operation | Time | Notes |
|---|---|---|
| Index / slice access | O(1) | Random access |
| Append / pop end | O(1)* | *Amortized |
| Insert / delete at index | O(n) | Elements shift |
Search (x in lst) |
O(n) | Linear scan |
| Sort | O(n log n) | list.sort() Timsort |
| Space | O(n) | Over-allocation for growth |
Elements live in a contiguous block. Size counts slots in use; capacity counts slots allocated (often larger, for amortized growth).
Interview essentials#
Amortized append: When capacity is full, Python allocates a larger block (typically ~1.125× growth) and copies elements — O(n) for that append, but O(1) amortized over many appends.
When to say list in interviews: default for sequential data, stack (append/pop), building results, two-pointer scans. Never use list.pop(0) or list.insert(0, x) in a loop — that is O(n²).
Sorted insert position — bisect: For maintaining sorted order with O(log n) lookup of insert index:
import bisect
nums = [1, 3, 5, 7]
i = bisect.bisect_left(nums, 4) # first index where 4 can be inserted
bisect.insort(nums, 4) # insert keeping sorted order
Useful when the problem needs "closest value in sorted data" or pairs with a sorted container pattern (e.g. LC 220 with balanced structure).
Python usage#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | |
Implementation of basic functions#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |