[Python-Dev] The `for y in [x]` idiom in comprehensions
Chris Barker
chris.barker at noaa.gov
Fri Feb 23 14:23:04 EST 2018
On Fri, Feb 23, 2018 at 10:45 AM, Guido van Rossum <guido at python.org> wrote:
> There are useful things you can only do with comprehensions if the second
> for-loop can use the variable in the first for-loop. E.g.
>
> [(i, j) for i in range(10) for j in range(i)]
>
indeed -- and that is fairly common use-case in nested for loops -- so good
to preserve this.
But I still think the original:
[g(y) for x in range(5) for y in [f(x)]]
Is always going to be confusing to read. Though I do agree that it's not
too bad when you unpack it into for loops:
In [89]: for x in range(5):
...: for y in [f(x)]:
...: l.append(g(y))
BTW, would it be even a tiny bit more efficient to use a tuple in the inner
loop?
[g(y) for x in range(5) for y in (f(x),)]
-CHB
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180223/b8ab47e2/attachment.html>
More information about the Python-Dev
mailing list