I can use if and for in list comprehensions/generator expressions as
list(i for i in range(100) if i*i < 30)
I know this is not the most efficient but bear with me as the condition could be much more complicated and this is just an example. However, this still goes through hundred iterations and only yields a value in the first 6. Is there a way to tell the generator expression where to stop with something like this:
list(i for i in range(100) while i*i < 30)
However, while is not understood in generator expressions. So, my question is, how do I write a generator expression with a stopping condition so it does not continue computation, even if it doesn’t yield new values.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Because the syntax of takewhile() and dropwhile() is not the clearest, here are the actual examples of your question:
>>> [i for i in itertools.takewhile(lambda x: x*x<30, range(10))] [0, 1, 2, 3, 4, 5] >>> [i for i in itertools.dropwhile(lambda x: x*x<30, range(10))] [6, 7, 8, 9]
Know that the author of itertools has questioned whether to deprecate these functions.
Method 2
The various functions in itertools (takewhile() comes to mind) can help.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0