127 private links
Comprehensions are a fantastic language feature in Python. They are an elegant alternative to manually constructing and populating data structures. Comprehensions are declarative – they just say what they are, as opposed to the implicit logic of manual looping. When it comes to simple object creation, comprehension should be used whenever possible. This goes not just for lists, but also for dictionaries and sets.
However, a widely perceived drawback to comprehensions is that they are harder to debug. When something goes wrong with a manual loop, the first thing to do is to print out the iterated values as they turn up. But the values of a list comprehension can’t be accessed, so print-debugging isn’t possible. To deal with this, it’s common to unravel the comprehension into a manual loop. Manual loops are uglier and more complicated and more error-prone than comprehensions, but that’s the price that must be paid for debuggability.