[Python-ideas] Variations on a loop

Bruce Leban bruce at leapyear.org
Thu Aug 28 07:07:51 CEST 2008


There are several different blocks of code you could tack onto a loop (I've
deliberately chosen somewhat unusual words to express these here):

    for x in items:
        # body
    interstitially:
        # things to do between loop iteration
        # (executed after each iteration in the loop when there is a next
value)
    subsequently:
        # things to do after the last element of the loop is processed
        # (when the loop is not exited by break)
    contrariwise:
        # things to do if the list was empty

For example:

    result = ""
    for x in items:
        result += str(x)
    interstitially:
        result += ", "
    contrariwise:
        result = "no data"

When I first learned that Python had an 'else' clause on loops, I assumed it
meant 'contrariwise'. I was surprised that it actually meant 'subsequently'.


To be more clear, contrariwise is essentially equivalent to:

    empty = True
    for x in items:
        empty = False
        # body
    if empty:
        # do contrariwise code

and interstitially is essentially equivalent to:

    first = True
    for x2 in items:
        if not first:
            # do interstitial code
            first = False
        x = x2
        # body

I think these are common/useful paradigms. I'm curious what others think.

--- Bruce
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20080827/52db181d/attachment.html>


More information about the Python-ideas mailing list