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 : l=
In : if l:
...: for e in l:
In : for e in :
In : for e in [1,2,3]:
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
if not l: # empty case for i in l: # only ever executed if there are any elements
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