How much computational work can we conceal behind a single line of Python? Quite a substantial amount, as it turns out. A loop may look perfectly innocent in the source code, yet the operations performed within it can introduce computational costs that are far from obvious. And what exactly are we measuring when we describe an algorithm as efficient? The number of iterations, the execution time, the memory allocated during computation, or the complexity of the operations performed at each iteration?
When analysing an algorithm, I pay particular attention to the relationship between its visible structure and its underlying computational behaviour. Consider a loop containing a membership test, a string operation or a function call. Each of these expressions occupies relatively little space in the source code, but each can initiate a considerably more complex computational process. Counting the number of loops without examining the operations they perform tells us remarkably little about the actual complexity of an implementation.
There is also an interesting misconception surrounding the brevity of code. A compact Python expression may be elegant, readable and mathematically expressive, but none of these qualities guarantees computational efficiency. A single line of code can allocate thousands of objects, repeatedly traverse a data structure or perform millions of comparisons. The interpreter is rather indifferent to our aesthetic preferences.
In this article, I want to dissect several familiar programming constructs and examine what happens beneath their syntactic simplicity. We will investigate iteration patterns, hidden quadratic complexity, amortised analysis, memory allocation and lazy evaluation, using Python to test our mathematical predictions against measurable computational behaviour.
After all, the cost of a loop is determined not simply by how often it repeats, but by what we have asked the machine to do each time it does.