One-liner to check whether an iterator yields at least one element?

后端 未结 9 1829
野的像风
野的像风 2020-12-05 01:45

Currently I\'m doing this:

try:
    something = iterator.next()
    # ...
except StopIteration:
    # ...

But I would like an expression th

9条回答
  •  渐次进展
    2020-12-05 02:20

    A little late, but... You could turn the iterator into a list and then work with that list:

    # Create a list of objects but runs out the iterator.
    l = [_ for _ in iterator]
    
    # If the list is not empty then the iterator had elements; else it was empty.
    if l :
        pass # Use the elements of the list (i.e. from the iterator)
    else :
        pass # Iterator was empty, thus list is empty.
    

提交回复
热议问题