Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to apply BREAK for Itertools count in List Comprehensions?

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?

like image 620
avimatta Avatar asked Oct 23 '16 10:10

avimatta


Video Answer


1 Answers

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]
like image 53
bereal Avatar answered Sep 24 '22 15:09

bereal