[Python-ideas] while conditional in list comprehension ?? (original) (raw)

Ian Cordasco graffatcolmingov at gmail.com
Tue Jan 29 02:43:22 CET 2013


On Mon, Jan 28, 2013 at 8:34 PM, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:

I was referring to the case of constructing an object that does not preserve order by iterating over an object that does. Clearly a while clause would be a lot less useful if you were iterating over an object whose order was arbitrary: so don't use it in that case.

Yeah, I'm not sure how well telling someone to use a construct of the language will go over.

A (contrived) example - caching Fibonacci numbers:

# Fibonacci number generator def fib(): a = b = 1 while True: yield a a, b = b, a+b # Cache the first N fibonacci numbers fibcache = {n: x for n, x in zip(range(N), fib())} # Alternative fibcache = {n: x for n, x in enumerate(fib()) while n < N}_ _# Cache the Fibonacci numbers less than X_ _fibcache = {}_ _for n, x in enumerate(fib()):_ _if x > X: break fibcache[n] = x # Alternative 1 fibcache = {n: x for n, x in enumerate(takewhile(lambda x: x < X, fib()))} # Alternative 2 fibcache = {n: x for n, x in enumerate(fib()) while x < X}

As contrived as it may be, it is a good example. Still, I dislike the use of while and would rather Steven's suggestion of until were this to be included. This would make until a super special case, but then again, this construct seems special enough that only a few examples of its usefulness can be constructed. I guess I'm more -0 with until than -1.

Thanks for the extra example Oscar. It was helpful.

Cheers, Ian



More information about the Python-ideas mailing list