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

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Mon Feb 26 04:40:27 EST 2018


Michel Desmoulin writes:

 > Le 25/02/2018 à 14:11, Nikolaus Rath a écrit :

>>>     result = [ (f(x) as y) + g(y) for x in range(10)]

 > Honestly I find this version the most readable while the double for
 > loop is completely weird to me, despite doing python for a living
 > for years.

I find this one less readable because I don't expect name binding
syntax to return a value.  My brain is nonplussed by the "+". :-)

 > I really hope the later doesn't become a common idiom.

It already is common, for values of "common" = "some people have been
using it where it's useful, but it's not useful all that often".  I
suppose it's rare because it's a less-than-readable optimization,
which is frowned on in Python programming.

Somebody counted four or five ways to perform this optimization,
including this "double for" that allows the common subexpression
optimization to be made explicit in the comprehension.  We don't need
another, not at the cost of new syntax.

If we find that we really want a C-like assignment expression that
returns the assigned value[1], I don't have an objection to that.  But
I don't personally feel a need for it.

Footnotes: 
[1]  Yes, I know that technically it's a local name binding, not an
assignment.  But until the scope of "local" is resolved, it looks,
smells, and tastes like an assignment.



More information about the Python-Dev mailing list