[Python-Dev] Re: listcomps vs. for loops

Terry Reedy tjreedy at udel.edu
Tue Oct 21 10:29:32 EDT 2003


"Michael Hudson" <mwh at python.net> wrote in message
news:2mad7uq0mr.fsf at starship.python.net...
> Guido van Rossum <guido at python.org> writes:
>
> > I don't recall what I said then.  Did I say it was a feature that
> >
> >   L = [x for x in R]
> >   print x
> >
> > would print the last item of R?

Someone more-or-less did -- in the tutorial.  See bottom below.

> A problem with such code irrespective of anything else is that it
> fails when R is empty.

Same would be true of for loops, except that typical after-for usage,
such as searching for item in list, has else clause to set control
variable to default in 'not found' cases, which include empty lists.

The Ref Manual currently says nothing about leakage or overwriting.
That should make leakage fair game for plugging.

On the other hand, Tutorial 5.1.4 List Comprehensions says:
'''
To make list comprehensions match the behavior of for loops,
assignments to the loop variable remain visible outside of the
comprehension:

>>> x = 100                     # this gets overwritten
>>> [x**3 for x in range(5)]
[0, 1, 8, 27, 64]
>>> x                           # the final value for range(5)
4
'''
(Pointed out by John Roth in response to my c.l.py posting.)
I have added note to SF 827209.

Terry J. Reedy






More information about the Python-Dev mailing list