Suggestion for impriving list comprehensions

Nick Perkins nperkins7 at home.com
Mon Jul 30 20:52:25 EDT 2001


"Guido van Rossum" <guido at python.org> wrote in message

> > [x for x in fib() while x < 50]
>
> Neat, but maybe not general enough.  How do you request the first N?

Similar to your idea, but takes an iterator:

def first(n,it):
    for i in xrange(n):
        yield it.next()

[ x for x in first(N,fib()) ]

This type of function could be written to take an iterator,
or a sequence, or even a generator.

..but I consider this unrelated to the question of allowing
'while' in a list comprehension.


> And fuzzy: does this include or exclude the first x >= 50?

Not fuzzy at all!
(exclude, of course)

The 'while' condition would work just like the 'if' condition:
Only values for which the condition is true would be included.
The only difference is that 'while' would terminate the
comprehension the first time it's condition is false.

In fact, the more I think about it, the more it seems like
a natural companion to the 'if' in a list comprehension.

The beauty of list comprehensions is that they
eliminate the drudgery of creating your own loop
just for the purpose of building a list.

The 'while' is list comprehensions looks just right to me.
It is easy to read and understand.


[ x for x in seq while x < 10 ]

means:

result=[]
for x in seq:
    if x < 10:
        result.append(x)
    else:
        break


This is just a tiny difference from the 'if' clause of a comprehension,
the only difference being the 'break'.

I don't see any really elegant alternative for implementing these
semantics..
( here's my try at it: )



## myresult = [ x for x in seq while x < 10 ]

def iter_while(it,test):
    while 1:
        val = it.next()
        if test(val):
            yield val
        else:
            raise StopIteration

myresult = [ x for x in iter_while(iter(seq),lambda x: x<10) ]



.. but this is, of course, pretty ugly.

( so let's have 'while' in list comprehensions! )








More information about the Python-list mailing list