Python 3.x: Test if generator has elements remaining

后端 未结 4 1241
旧巷少年郎
旧巷少年郎 2021-02-04 00:56

When I use a generator in a for loop, it seems to \"know\", when there are no more elements yielded. Now, I have to use a generator WITHOUT a for loop, and use next

4条回答
  •  忘了有多久
    2021-02-04 01:41

    This may not precisely answer your question, but I found my way here looking to elegantly grab a result from a generator without having to write a try: block. A little googling later I figured this out:

    def g():
        yield 5
    
    result = next(g(), None)
    

    Now result is either 5 or None, depending on how many times you've called next on the iterator, or depending on whether the generator function returned early instead of yielding.

    I strongly prefer handling None as an output over raising for "normal" conditions, so dodging the try/catch here is a big win. If the situation calls for it, there's also an easy place to add a default other than None.

提交回复
热议问题