Reputation: 980
I'm working with a generator and I have the code below. I'm a little confused about its logic.
The generator in the function works fine as long as there is a 'False' at the end. Removing it causes a StopIteration
exception when running the function.
Can anybody explain me the role of False
here?
>>> def some(coll, pred= lambda x:x)
... return next((True for item in coll if pred(item)),False)
...
>>> some([0,'',False])
False
>>> def some(coll, pred= lambda x:x):
... return next((True for item in coll if pred(item)))
...
>>> some([0,'',False])
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
some([0,'',False])
File "<pyshell#63>", line 2, in some
return next((True for item in coll if pred(item)))
StopIteration
Upvotes: 0
Views: 1134
Reputation: 1122152
You are passing in a default value for the next()
function to return if the generator expression raises a StopIteration
exception. The False
is the default value returned here:
Retrieve the next item from the iterator by calling its
__next__()
method. If default is given, it is returned if the iterator is exhausted, otherwiseStopIteration
is raised.
Raising StopIteration
is how iterators communicate that they are done and can no longer be used to produce results. Generators are a specialised type of iterator.
You don't have to pass in False
; any valid Python value will do. If you omit the default argument, you can also omit the generator parenthesis:
next(True for item in coll if pred(item))
Upvotes: 3