4 ms·
I may be the outlier here, but I have a very hard time comprehending list comprehensions. They've always seemed like a SQL query compressed into a single line (
by von_lohengramm 4y ago
I may be the outlier here, but I have a very hard time comprehending list comprehensions. They've always seemed like a SQL query compressed into a single line (or two if you're lucky!): readable when it's simple, Lovecraftian when it's not. I've always found the functional pipeline style much more readable and much easier to explain to others, especially with IDE type hints.
- int_19h 4y agoSQL queries are sequence comprehensions! Python comprehensions in particular are unfortunate because the flow of the query, like in SQL, is not linear - the projection part is written first, but happens last. Thus, reading a non-trivial query requires moving back and forth to resolve the references. Compare that to C# LINQ, which is also a kind of sequence comprehension. That one not only has linear syntax where the data flow in the query is strictly left to right, but it's explicitly defined by mapping it to functional pipeline style. Thus, it ends up being a strict improvement on the latter. (Another example of "good" sequence comprehensions in this sense is XQuery FLWOR)
- maxbond 4y agoIMHO the key to legible comprehensions is to use them only to express composition and to put the logic into verbosely named functions. Chained pipelines (`foo.filter(...).map(...)`) are fine to me, certainly more verbose then comprehensions for better & worse, but I get lost in pipelines expressed as nested functions (`map(filter(a, ...), ...)`).
- dragonwriter 4y ago> they’ve always seemed like a SQL query compressed into a single line (or two if you’re lucky!): If its more than a very simple expression, with one simple for, and no if or very simple if, I try to use at least (more, with parens, if necessary): one line for the result expression, one line for each for clause, and one line for each if clause. But, while the boundary is subjective, it doesn’t take much before functional pipeline style is clearer (Python lambdas being more limited and syntacticaly cumbersome, functional pipeline style isn’t as clean in Python as it is in other languages, though.)
- snowpid 4y agoit depends on your problem but in many cases simple is enough imho. There are map and filter in python avalaible. I just didnt need to use them.