[Python-Dev] The `for y in [x]` idiom in comprehensions

Stefan Behnel stefan_ml at behnel.de
Fri Feb 23 04:12:25 EST 2018


Stephen J. Turnbull schrieb am 23.02.2018 um 03:31:
> Barry Warsaw writes:
>  > rather than having to pause to reason about what that 1-element
>  > list-like syntax actually means, and 2) will this encourage even
>  > more complicated comprehensions that are less readable than just
>  > expanding the code into a for-loop?
> 
> Of course it will encourage more complicated comprehensions, and we
> know that complexity is less readable.  On the other hand, a for loop
> with a temporary variable will take up at least 3 statements vs. a
> one-statement comprehension.

IMHO, any complex comprehension should be split across multiple lines,
definitely if it uses multiple for-loops, as in the discussed example. So
the "space win" of a complex comprehension that requires temporary values
over a multi-line for-statement is actually not big in these cases.

There are certainly cases where a comprehension still looks better, but I'm
all for not encouraging a hacky idiom to stuff more into a comprehension.
Comprehensions should be used to *improve* readabilty, not to reduce it.

Stefan



More information about the Python-Dev mailing list