Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminating generator expression [duplicate]

I'm having a mental block, is there a usual python 1-liner for terminating a list comprehension or genex based on some condition? Example usage:

def primes():
  # yields forever e.g. 2, 3, 5, 7, 11, 13 ... 

[p for p in primes() if p < 10]
# will never terminate, and will go onto infinite loop consuming primes()

[p for p in primes() while p < 10]
# should return [2, 3, 5, 7], and consumed 5 items from my generator

I know about itertools consume, islice, but those guys require you to know how many items you want to consume in advance.

like image 864
wim Avatar asked Dec 01 '25 08:12

wim


1 Answers

You can use itertools.takewhile:

itertools.takewhile(lambda x: x < 10, primes())

or… if you want to avoid lambda:

itertools.takewhile((10.).__gt__, primes())
like image 188
eumiro Avatar answered Dec 02 '25 22:12

eumiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!