Reputation: 21991
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?
Upvotes: 4
Views: 2825
Reputation: 42490
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)))
Upvotes: 2