[Python-Dev] Re: listcomps vs. for loops
Guido van Rossum
guido at python.org
Tue Oct 21 12:58:23 EDT 2003
> > > 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.
Oh bah!
> > 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 regular for loop won't change.
> The Ref Manual currently says nothing about leakage or overwriting.
> That should make leakage fair game for plugging.
Unfortunately the Ref Manual is notoriously incomplete.
> 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.
Sigh. What a bummer to put this in a tutorial. :-(
But it won't stop me from deprecating the feature.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev
mailing list