Suggestion for impriving list comprehensions

Steven D. Majewski sdm7g at Virginia.EDU
Thu Jul 26 20:53:34 EDT 2001

```On Thu, 26 Jul 2001, Guido van Rossum wrote:

> paul at svensson.org (Paul Svensson) writes:
>
> > I would like to suggest that we add a "while condition" clause
> > to list comprehensions, similar to the "if condition" clause,
> > but terminating the list comprehension on the first false condition.
> > The above example could then be written as
> >
> > [x for x in fib() while x < 50]
>
> Neat, but maybe not general enough.  How do you request the first N?
> And fuzzy: does this include or exclude the first x >= 50?
>
> How about a library of functions for iterator algebra?  E.g.
>

>>> def dowhile( seq, test ):
...     for x in seq:
...             if test(x): yield x
...             else: break
...
>>> def until( seq, test ):
...     for x in seq:
...             yield x
...             if test(x) : break
...
>>> [ x for x in until( range(100), lambda x: x > 12 ) ]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
>>> [ x for x in until( fib(), lambda x: x > 50 ) ]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> [ x for x in dowhile( fib(), lambda x: x < 50 ) ]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
>>>

( where fib is the generator version )

And maybe, Icon inspired:

>>> def every( s ):
...     return [ x for x in s ]

>>> every( range(10) )
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> every( iter( fib().next, 55 ) )
[1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> every( dowhile( fib(), lambda x: x < 50 ))
[1, 1, 2, 3, 5, 8, 13, 21, 34]
>>>

If there was a version of iter that was:
iter( genfunc, boolfunc )
along with:
iter( genfunc, sentinal )

But checking for whether the second arg is callable is no good
if it's possible to iterate thru functions,methods or classes.

Maybe a three arg version:
iter( genfunc, sentinal, boolfunc )

and if you don't care about the sentinal, pass an arg that won't
be produced by the generator. ( None maybe, depending. )

[ But maybe the generator versions above are better.
I'm still getting used to this new stuff.
Sometimes the syntax seems a bit awkward.
I hope that this __future__ stuff is not cast in stone until
we've had time to see how it works.  ]

-- Steve Majewski

```