how to apply BREAK for Itertools count in List Comprehensions?
python, python-3.x, python-itertools
Solution
There's no `break` inside list comprehensions or generator expressions, but if you want to stop on a certain condition, you can use `takewhile`:
>>> from itertools import takewhile, count
>>> list(takewhile(lambda x: x < 20, count(5, 2)))
[5, 7, 9, 11, 13, 15, 17, 19]
Problem
if this is duplicate, already answered then sorry, i didn't came across this question as i was reading itertools count, generating an iterator using for loop is easy, and i was trying to do that in list comprehension but i am facing this problem ``` from itertools import * ``` by using for loop ``` for x in itertools.count(5,2): if x > 20: break else: print(x) 5 7 9 11 13 15 17 19 ``` i tried to do this in list comprehension ``` [x if x<20 else break for x in count(5,2)] File "<ipython-input-9-436737c82775>", line 1 [x if x<20 else break for x in count(5,2)] ^ SyntaxError: invalid syntax ``` i tried with islice method and i got the answer ``` [x for x in itertools.islice(itertools.count(5),10)] [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] ``` without using islice method, how can I exit(using break or any thing) by using only count method? additionally how to implement `break` in `list comprehensions`?