[Python-Dev] Enhancing `iter'
bob at redivi.com
Wed Feb 18 17:38:19 EST 2004
On Feb 18, 2004, at 8:07 AM, Miki Tebeka wrote:
> Currently `iter' 2'nd parameter is used for comparison.
> I'd like to have the ability to give a function that will determine
> to stop or not.
> iter(range(10), lambda x: x > 7)
> will stop at 8.
> (There reverse logic might be uses as well: continue as long a
> returns True.)
> The only problem I can see is that someone might want to use a function
> object as a sentinal, then `iter' won't know if to call the function
> or to
> compare. However this seems very rare and can be solved by:
> def f(x, y):
> iter(something, lambda x: x == f)
This is not necessary.
>>> import itertools
>>> list(itertools.takewhile(lambda x: x < 8, range(10)))
[0, 1, 2, 3, 4, 5, 6, 7]
(among the numerous other ways to say it with itertools .. or even
generator comprehensions in Python 2.4)
More information about the Python-Dev