handle handle - 1 month ago 14
Python Question

Is there a construct like "iterate iterable if it has elements, else ..."?

Is there a more compact way to iterate an iterable if it has elements, or do something else if it hasn't?

My "problem" is in Python but I'd be interested in other languages as well.

Currently I test the number of elements first:

In [1]: l=[]

In [2]: if l:
...: for e in l:
...: print(e)
...: else:
...: print("else")
...:
else


The
for
statement has an
else
:

In [2]: for e in []:
...: print(e)
...: else:
...: print("else")
...:
else


but its "suite" (block) is also executed when the iteration is completed:

In [1]: for e in [1,2,3]:
...: print(e)
...: else:
...: print("else")
...:
1
2
3
else


I realize there is not much to gain here (one line and indent level) but I am curious if something like this exists.

Answer

Most of the time you just test for length and exit early:

if not l:
    # empty case
    return  # or raise exception

At any rate, because iteration will not take place on an empty list, the following is also sufficient, no else required:

if not l:
    # empty case
for i in l:
    # only ever executed if there are any elements

The for ... else suite is only useful for loops that exit early; the else suite is executed for all loops that completed. If a break was used the else is skipped. This makes it unsuitable for detecting empty sequences, as iteration on those completes successfully regardless of the number of elements in the absence of a break statement.