[Python-ideas] while conditional in list comprehension ??

Shane Green shane at umbrellacode.com
Mon Jan 28 15:51:23 CET 2013


Yeah, I realized (1) after a minute and came up with "else break": if n < 400 else break.  Could that be functionally equivalent, not based on a loop construct within an iterator?





Shane Green 
www.umbrellacode.com
408-692-4666 | shane at umbrellacode.com

On Jan 28, 2013, at 6:43 AM, Chris Angelico <rosuav at gmail.com> wrote:

> On Tue, Jan 29, 2013 at 1:32 AM, Shane Green <shane at umbrellacode.com> wrote:
>> Isn't "while" kind just the "if" of a looping construct?
>> 
>> Would [n for n in range(1,1000) while n < 400] == [n for n in range(1,1000)
>> if n < 400]?
>> 
>> I guess your kind of looking for an "else break" feature to exit the list
>> comprehension before evaluating all the input values.  Wouldn't that
>> complete the "while()" functionality?
> 
> In the specific case given, they'll produce the same result, but there
> are two key differences:
> 
> 1) If the condition becomes true again later in the original iterable,
> the 'if' will pick up those entries, but the 'while' won't; and
> 2) The 'while' version will not consume more than the one result that
> failed to pass the condition.
> 
> I daresay it would be faster and maybe cleaner to implement this with
> a language feature rather than itertools.takewhile, but list
> comprehensions can get unwieldy too; is there sufficient call for this
> to justify the syntax?
> 
> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130128/1272c96c/attachment.html>


More information about the Python-ideas mailing list