Reputation: 8059
When using infinite generators, I can use if
to prevent items from entering the list, but not in order to break the loop.
This will actually crash and hang. Not even KeyboardInterrupt
can save me (why is that BTW?)
import itertools
a = [x for x in itertools.count() if x<10]
While if I use my own infinite generator
def mygen():
i=0
while True:
yield i
i +=1
this will run until KeyboardInterrupt
a = [x for x in mygen() if x<10]
Now, obviously for a proper for
loop we can break when a condition is met
a = []
for x in itertools.count():
a.append(x)
if x>9:
break
So my question: Is there some way to break out of list comprehension?
Upvotes: 2
Views: 1440
Reputation: 142206
Use itertools.takewhile
to cease iteration after a condition is no longer met...:
import itertools
a = [x for x in itertools.takewhile(lambda L: L < 10, itertools.count())]
# a = list(itertools.takewhile(lambda L: < 10, itertools.count()))
There's isn't per-se a way to break out of a list-comp, so limiting the iterable (takewhile
or islice
etc... is the way to go...)
Upvotes: 7