On Mon, Jan 28, 2013 at 8:34 PM, Oscar Benjamin oscar.j.benjamin@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 fib_cache = {n: x for n, x in zip(range(N), fib())} # Alternative fib_cache = {n: x for n, x in enumerate(fib()) while n < N}
# Cache the Fibonacci numbers less than X fib_cache = {} for n, x in enumerate(fib()): if x > X: break fib_cache[n] = x # Alternative 1 fib_cache = {n: x for n, x in enumerate(takewhile(lambda x: x < X, fib()))} # Alternative 2 fib_cache = {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