[Python-Dev] The `for y in [x]` idiom in comprehensions
Stephen J. Turnbull
turnbull.stephen.fw at u.tsukuba.ac.jp
Thu Feb 22 21:31:11 EST 2018
Barry Warsaw writes:
> My questions are 1) will this become idiomatic enough to be able to
> understand at a glance what is going on,
Is it similar enough to
def f(x=[0]):
which is sometimes seen as a way to produce a mutable default value
for function arguments, to be "idiomatic"?
> 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.
I don't have an opinion about the equities there. I myself will
likely use the [(y, f(y)) for x in xs for y in costly(x)] idiom very
occasionally, with emphasis on "very" (for almost all "costly"
functions I might use that's the Knuthian root of error). But I don't
know how others feel about it.
Steve
More information about the Python-Dev
mailing list