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
iterator
is 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() #?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…