user308827
user308827

Reputation: 21991

How can I find length of iterator in python without exhausting it?

I have the following use case:

  1. Call a function which returns iterator in python
  2. Check if iterator is not empty
  3. If not empty, then do some operation

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

Answers (1)

Andrew Walker
Andrew Walker

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

Related Questions