for: else: - any practical uses for the else clause?

Peter Otten __peter__ at web.de
Sat Sep 30 04:31:25 EDT 2006


Sybren Stuvel wrote:

> Paul Rubin enlightened us with:
>>> height = 0
>>> for block in stack:
>>>     if block.is_marked():
>>>         print "Lowest marked block is at height", height
>>>         break
>>>     height += block.height
>>> else:
>>>     raise SomeError("No marked block")
>>
>>     all_heights = [block.height for block in stack if block.is_marked()]
>>     if all_heights:
>>       height = sum(all_heights)
>>     else:
>>       raise SomeError("No marked block")
>>
>> Alternatively (lower memory usage for large list):
>>
>>     all_heights = (block.height for block in stack if block.is_marked())
>>     try:
>>       height = all_heights.next()
>>       height += sum(all_heights)
>>     except StopIteration:
>>       raise SomeError("No marked block")
> 
> I must say that the for/else construct is a LOT more readable than the
> rewritten alternatives.

I like

def blocks_til_mark(stack):
    for block in stack:
        if block.is_marked():
            return
        yield block
    raise SomeError
height = sum(block.height for block in blocks_til_mark(stack))

Peter



More information about the Python-list mailing list