I have the following use case:
However, the process of checking if the iterator is empty, seems to empty it. Is there a better way to do this?
To get a copy of an iterator so that you can operate on it independently of the original, you can use itertools.tee. You can test if an iterator is empty by seeing if it throws StopIteration.
So you could do something like:
def isempty(it):
try:
itcpy = itertools.tee(it,1)[0]
itcpy.next()
return False
except StopIteration:
return True
def empty_iterator():
if False:
yield
it = empty_iterator()
if not isempty(it):
# won't print
print(len(list(it)))
it = xrange(4)
if not isempty(it):
# will print
print(len(list(it)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With