Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 262
user308827 Avatar asked Oct 28 '25 05:10

user308827


1 Answers

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)))
like image 197
Andrew Walker Avatar answered Oct 29 '25 19:10

Andrew Walker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!