[Python-Dev] The `for y in [x]` idiom in comprehensions
Guido van Rossum
guido at python.org
Fri Feb 23 13:45:20 EST 2018
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)]
On Fri, Feb 23, 2018 at 10:16 AM, Chris Barker <chris.barker at noaa.gov>
wrote:
> On Fri, Feb 23, 2018 at 9:51 AM, Guido van Rossum <guido at python.org>
> wrote:
>
>> As to the validity or legality of this code, it's both, and working as
>> intended.
>>
>> A list comprehension of the form
>>
>> [STUFF for VAR1 in SEQ1 for VAR2 in SEQ2 for VAR3 in SEQ3]
>>
>> should be seen (informally) as
>>
>> for VAR1 in SEQ1:
>> for VAR2 in SEQ2:
>> for VAR3 in SEQ3:
>> "put STUFF in the result"
>>
>
> Thanks -- right after posting, I realized that was the way to unpack it to
> understand it. I think my confusion came from two things:
>
> 1) I usually don't care in which order the loops are ordered -- i.e., that
> could be:
>
> for VAR3 in SEQ3:
> for VAR2 in SEQ2:
> for VAR1 in SEQ1:
> "put STUFF in the result"
>
> As I usually don't care, I have to think about it (and maybe experiment to
> be sure). (this is the old Fortran vs C order thing :-)
>
> 2) since it's a single expression, I wasn't sure of the evaluation order,
> so maybe (in my head) it could have been (optimized) to be:
>
> [STUFF for VAR1 in Expression_that_evaluates_to_an_iterable1 for VAR2 in
> Expression_that_evaluates_to_an_iterable2]
>
> and that could translate to:
>
> IT1 = Expression_that_evaluates_to_an_iterable1
> IT2 = Expression_that_evaluates_to_an_iterable2
> for VAR1 in IT1:
> for VAR2 in IT2:
> "put STUFF in the result"
>
> In which case, VAR1 would not be available to Expression_that_evaluates_
> to_an_iterable2.
>
> Maybe that was very wrong headed -- but that's where my head went -- and
> I'm not a Python newbie (maybe an oddity, though :-) )
>
> -CHB
>
>
> --
>
> Christopher Barker, Ph.D.
> Oceanographer
>
> Emergency Response Division
> NOAA/NOS/OR&R (206) 526-6959 voice
> 7600 Sand Point Way NE
> <https://maps.google.com/?q=7600+Sand+Point+Way+NE&entry=gmail&source=g>
> (206) 526-6329 fax
> Seattle, WA 98115 (206) 526-6317 main reception
>
> Chris.Barker at noaa.gov
>
--
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180223/df12cc00/attachment.html>
More information about the Python-Dev
mailing list