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

Chris Barker - NOAA Federal chris.barker at noaa.gov
Fri Feb 23 12:41:50 EST 2018


> Is it similar enough to
>
>    def f(x=[0]):

No, not at all — it’s a very different use case.

When I first saw this on the original thread, I needed to stare at it
a good while, and then whip up some code to experiment with it to know
what it did.

And not because I don’t know what a single element list means, or what
it means to iterate over a single element list, or what two fors mean
in a comprehension.

I was confused by the ‘x’ in the second iterable. I guess I’m (still)
not really clear on the scope(s) inside a comprehension, and when the
elements get evaluated in a list.

I expected that the list would be created once, with the value x had
initially, rather than getting the-evaluated each time through the
outer loop.

So I think that it is a very confusing use of comprehensions, and
always will be. I’m still surprised it’s legal. Anyone know if this
being allowed was deliberate or just kind of fell out of the
implementation?

So no, I don’t think it should be promoted as idiomatic.

All that being said, it’s valid Python, so why not optimize it?

-CHB


More information about the Python-Dev mailing list