Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

python - Loop over empty iterator does not raise exception

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the Statements, and else Clauses on Loops.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable.

For example:

iterator = []
for element in iterator:
    print('This wont print..')
else:
    assert iterator

This will results with:

Traceback (most recent call last):
  File "<pyshell#2>", line 4, in <module>
    assert iterator
AssertionError

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...