The following example:
def myGenerator(): i = -1 while i < 1000000: print(f"iterating {i}") i+=1 yield iprint(9999 in myGenerator())
Prints in the console
...iterating 9994iterating 9995iterating 9996iterating 9997iterating 9998True
The generator iterates over all items until it finds '9999'(which in the end of the day then makes it rather pointless to use a generator to begin with as opposed to having my function return a tuple or a list).
Would it be possible to define __contains__
on the Generator()
object returned by my myGenerator
function to avoid iterating over all items ? If so, how?