comprehensions was Re: Switch statements again

Beni Cherniavsky cben at
Mon Jan 20 18:04:01 CET 2003

On 2003-01-19, Dave Brueck wrote:

> On Sun, 19 Jan 2003, Beni Cherniavsky wrote:
> >
> > > At the time, lexical nesting didn't yet exist in Python either.
> > > The case for "magically local" bindings has gotten stronger since
> > > lexical nesting was added, but now we've got a backwards
> > > compatibility burden too.
> > >
> > There is one central use for leaving the binding alive in for loops:
> > when you can exit it prematurely and want to record where you did.
> > This is one thing missing from list comprehensions - a way to break in
> > the middle.
> I dunno - IMO a list comprehension is for building a list from another
> list, so the only legitimate reasons for breaking out prematurely would
> be some sort of optimization on processing ordered lists or maybe some
> sort of "select first n occurences of f(x)" or something - cases not
> common enough to warrant special list comp behavior since such needs can
> be handled much better by plain for loops.
Well, you are probably right.  It's usually simpler to just find the place
you need and splice (before or after the comprehension), or use a loop.

> > Especially needed when iterating over infinite interators
> But why use a list comprehension for that?
Because you will be able to <wink> (currently you can't because it will
never stop [1]_).  Actually you will want to use generator comprehensions
for that.  Anyway, you'll frequently need some consvenient way to make
finite sequences from an infinite generators.

.. [1] This might solve it now::

    def xwhile(func, iterable):
        for x in iterable:
	    if not func(x):
            yield x

                 -while-have-time-ly y'rs
    Beni Cherniavsky <cben at>

More information about the Python-list mailing list