[Python-Dev] listcomps vs. for loops
Walter Dörwald
walter at livinglogic.de
Wed Oct 22 13:21:56 EDT 2003
Guido van Rossum wrote:
> [...]
> The variable of a for *statement* must be accessible after the loop
> because you might want to break out of the loop with a specific
> value. This is a common pattern that I have no intent of breaking.
> So it can't introduce a new scope; then it might as well keep the last
> value assigned to it.
>
> List comprehensions and generator expressions don't have 'break'.
> (You could cause an exception and catch it, but it's not a common
> pattern to use the control variable afterwards -- only the debugger
> would need access somehow.)
How about an until keyword in generator expressions:
sum(len(line) for line in file if not line.startswith("#") until not
line.strip())
Would the order of "if" and "until" be significant?
And we could have accumulators first() and last():
def first(it):
return it.next()
def last(it):
for value in it:
pass
return value
first(line for line in file if line.startswith("#"))
if not last(file):
# last line not terminated
Bye,
Walter Dörwald
More information about the Python-Dev
mailing list