6

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?

4
  • Why don't you like islice? There's definitely no break inside list comprehension, but there's takewhile. Commented Oct 23, 2016 at 10:23
  • 1
    Why don't you use range(5, 20, 2) or range(5, 15) ? Commented Oct 23, 2016 at 10:25
  • it's not about liking, i just want to know that "can i do in this way or not?" @bereal Commented Oct 23, 2016 at 10:26
  • i can use range, as i was reading itertools, i tried to do with itertools @falsetru Commented Oct 23, 2016 at 10:29

1 Answer 1

7

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] 
Sign up to request clarification or add additional context in comments.

6 Comments

You can list(takewhile(int(20).__gt__, count(5, 2))) to remove the ugly lambda and it will be quite a but faster.
@PadraicCunningham faster yes, but I would perhaps question the comparative ugliness.
I meant ugly as much for the overhead as the visual representation, a lambda with any functional code is the kiss of death for performance which is generally what you are trying to achieve when using itertools, map, filter etc.
@avimatta You can also accept the answer, this is the greatest "Thank you, it works!"
@PadraicCunningham can you tell me "a lambda with any functional code is the kiss of death for performance?"
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.