Bob Ippolito (@etrepum) on Haskell, Python, Erlang, JavaScript, etc.
«

for loops and empty iterables

»

Just van Rossum and I were discussing the for:else:, while:else: and try:else: syntax on the MacPythonChannel this morning (morning for me, at least). I'm not sure if this is sufficiently covered elsewhere, but here is the pattern I use to check for empty iterables:

class NoValue:
    """A unique placeholder, since None is sometimes used in iterables"""

def doesSomethingWithIterable(iterable):
    x = NoValue
    for x in iterable:
        pass # something useful could go here ;)
    else:
        if x is NoValue:
            pass # do something because iterable was empty
        else:
            pass # do something because iterable was not empty