[x for x in <> while <>]?

Ruediger larudwer at freenet.de
Sat May 17 06:08:51 EDT 2008


urikaluzhny wrote:

> It seems that I rather frequently need a list or iterator of the form
> [x for x in <> while <>]
> And there is no one like this.
> May be there is another short way to write it (not as a loop). Is
> there?
> Thanks

I usually have the same problem and i came up with an solution like that:

from operator import ne
def test(iterable, value, op=ne):
    _n = iter(iterable).next
    while True:
        _x = _n()
        if op(_x, value):
            yield _x
        else:
            raise StopIteration

l = range(6)
print [x for x in test(l, 4)]

r at linux:~/tmp> python test18.py
[0, 1, 2, 3]




More information about the Python-list mailing list