I am on Python 3.6.7.
I just noticed that a for loop over an empty list does not loop even once.
After some thought, that made some sense to me. I.e. a loop over a zero-sized (empty) object returns zero iterations.
iterable = []
for element in iterable:
pass
print(element)
>>> NameError: name 'element' is not defined
This means that a test inside the loop will not be executed if len(iterable) == 0.
iterable = []
for element in iterable:
assert isinstance(element, int)
#nothing happens
Then how can I catch this situation?
Is there a compact built-in way to raise an error when my loop does not run because the iterable is empty?
Catching this particular situation requires manually:
- testing that the
iteratoris non-empty before the loop - testing that the element was defined, after the loop. Neither method seems elegant to me
And I may end up having this test in every single for loop.
assert len(iterable) > 0
#loop
or
#loop
assert "element" in dir() #?
assert len(iterator) > 0you can just useassert iterator- empty iterators are Falsey:bool([]) == False. - CDJBIs there a compact built-in way to raise an error when my loop does not run because the iterable is empty?) - Andrea Massettiiteratorwithiterable- Andrea Massetti