CPython's list over-allocates extra capacity beyond the current size whenever it needs to grow, so most append() calls just write into already-allocated space (O(1)); only occasionally, when capacity is exhausted, does it need to allocate a larger buffer and copy all elements (O(n)) — averaged ('amortized') across many appends, this works out to O(1) per append.
import sys
lst = []
for i in range(10):
lst.append(i)
print(len(lst), sys.getsizeof(lst)) # size (in bytes) jumps in chunks, not every single append
Real-world example
Understanding why appending to a Python list in a loop is generally efficient, despite lists being resizable arrays rather than linked lists.
Likely follow-ups
How does this over-allocation strategy differ from what happens when you use list.insert(0, x) repeatedly instead of append()?
Declaring __slots__ = ("attr1", "attr2", ...) on a class tells Python to allocate FIXED, pre-defined storage slots for those specific attributes instead of giving each instance a dynamic __dict__ — significantly reducing per-instance memory overhead, especially valuable when creating MANY instances of a small class.
class Point:
__slots__ = ("x", "y") # no per-instance __dict__ allocated
def __init__(self, x, y):
self.x = x
self.y = y
# point.z = 5 # would raise AttributeError -- no __dict__, no arbitrary new attributes
Real-world example
Reducing memory usage significantly when creating millions of small objects, like Point instances in a large point cloud dataset.
Likely follow-ups
What capability do you LOSE by using __slots__, like the ability to add new attributes dynamically?
CPython's dict implementation (since 3.6 as an implementation detail, guaranteed by the language spec since 3.7) uses a COMPACT internal representation: a separate, order-preserving array of entries alongside a sparse hash table of INDICES into that array — this achieves both O(1) average hash-based lookup AND stable insertion-order iteration, unlike the older implementation which stored entries directly in hash-table slot order.
d = {}
d["z"] = 1
d["a"] = 2
d["m"] = 3
print(list(d.keys())) # ['z', 'a', 'm'] -- insertion order preserved, NOT alphabetical or hash order
Real-world example
Relying on dict insertion order being preserved for building an ordered configuration or an ordered API response body.
Likely follow-ups
Before Python 3.7, what dedicated class from the collections module was needed to guarantee this same ordering behavior?
Standard Library Essentials (collectionsitertools)
Counter is a dict subclass specialized for counting hashable items — pass it any iterable to get automatic frequency counts, and use .most_common(n) to efficiently retrieve the top N most frequent elements without writing manual counting logic.
from collections import Counter
words = "the quick brown fox jumps over the lazy dog the fox runs".split()
counts = Counter(words)
print(counts["the"]) # 3
print(counts.most_common(2)) # [('the', 3), ('fox', 2)]
Real-world example
Analyzing word frequency in a large text corpus, or finding the most common error codes in a log file.
Likely follow-ups
How does Counter support arithmetic operations like addition and subtraction between two Counter objects?
Standard Library Essentials (collectionsitertools)
heapq.nsmallest(k, iterable) or heapq.nlargest(k, iterable) is generally the most efficient choice for finding just K elements from a large dataset (O(n log k) rather than sorting the ENTIRE dataset at O(n log n) with sorted()[:k]) — a plain sort is simpler and fine for small datasets, but heapq scales much better when the dataset is large and K is small relative to it.
import heapq
scores = [45, 92, 78, 12, 88, 67, 99, 34]
top_3 = heapq.nlargest(3, scores)
print(top_3) # [99, 92, 88] -- more efficient than sorted(scores, reverse=True)[:3] for large datasets
Real-world example
Finding the top 10 highest-scoring results from a dataset of millions of records without fully sorting the entire dataset.
Likely follow-ups
At roughly what ratio of K to total dataset size does heapq's efficiency advantage over a full sort become negligible?