3 ms·
There is a fundamental difference between the loop and the comprehension: the latter is far more declarative. I completely agree with this, and the wider funda
by Chris_Newton 14y ago
There is a fundamental difference between the loop and the comprehension: the latter is far more declarative.
I completely agree with this, and the wider fundamental point throughout your post.
However, I’m not a fan of comprehension syntax. It often gets noisy even for trivial cases like this one: the letters “number” appear four times in just a single line here, which as it turns out is just as much accidental complexity as using the explicit loop control variable in the imperative version and you’ve lost the visual cues to what each means that the indentation gives with the loop. For more complicated transformations, I find comprehension syntax also scales poorly.
I suspect (though I’ve no hard data to back it up) that comprehension syntax actually isn’t very readable in many cases, and that this may be why some people prefer the kind of code in the imperative example rather than any innate preference for imperative style per se. Personally, I’d prefer to highlight the data flow but using more explicit transformations instead, such as (in a hypothetical functional programming syntax):
evens = filter {_ % 2 == 0} numbers
Python’s own syntax for this isn’t quite as neat as some functional programming languages, IMHO, but I still prefer it to the comprehension:
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda n: n % 2 == 0, numbers)
- thezilch 14y agoTo be fair, we should be comparing like tokens, if the proof is using them as part of its advantage: evens = filter(lambda n: n % 2 == 0, numbers) with evens = [n for n in numbers if n % 2 == 0] or evens = [n for n in numbers if not n % 2] Choosing token names is certainly a different
- Chris_Newton 14y agoFair comment. I suppose that’s why a more declarative style tends to work much better in a language designed for it. For example, functional programming languages tend to have neat syntactic sugar for things like simple lambda expressions or applying a series of transformations like the filter here, without introducing accidental complexity like extra identifiers that the reader than has to keep track of. The moment you’ve added that kind of baggage, which is almost inevitable to some degree in a language like Python, the clarity tends to suffer.