21

I can use if and for in list comprehensions/generator expressions as

list(i for i in range(100) if i*i < 30)

I know this is not the most efficient but bear with me as the condition could be much more complicated and this is just an example. However, this still goes through hundred iterations and only yields a value in the first 6. Is there a way to tell the generator expression where to stop with something like this:

list(i for i in range(100) while i*i < 30)

However, while is not understood in generator expressions. So, my question is, how do I write a generator expression with a stopping condition so it does not continue computation, even if it doesn't yield new values.

Eric
  • 95,302
  • 53
  • 242
  • 374
highBandWidth
  • 16,751
  • 20
  • 84
  • 131
  • 1
    Just a note: you can generate a list directly by using `[i for i in range(100)]` – Joril Mar 31 '11 at 20:29
  • 1
    Curiously, there was [PEP3142](https://www.python.org/dev/peps/pep-3142/) open at the time this question was asked. The use case given is almost exactly this one. Guido nuked it in May, 2013 – John La Rooy Aug 28 '15 at 07:12

2 Answers2

27

Because the syntax of takewhile() and dropwhile() is not the clearest, here are the actual examples of your question:

>>> [i for i in itertools.takewhile(lambda x: x*x<30, range(10))]
[0, 1, 2, 3, 4, 5]
>>> [i for i in itertools.dropwhile(lambda x: x*x<30, range(10))]
[6, 7, 8, 9] 

Know that the author of itertools has questioned whether to deprecate these functions.

dawg
  • 98,345
  • 23
  • 131
  • 206
  • What would be the recipe in case these functions are deprecated? – highBandWidth Sep 01 '11 at 21:40
  • Just look at the Python docs for [itertools.takewhile](http://docs.python.org/library/itertools.html#itertools.takewhile) and [itertools.dropwhile](http://docs.python.org/library/itertools.html#itertools.dropwhile). Each has the straight Python equivalent. – dawg Sep 01 '11 at 23:54
  • 7
    isn't just `list(itertools.takewhile(lambda x: x*x<30, range(10)))` easier than a comprehension here – wim Mar 14 '13 at 12:15
  • @wim I pointed the link at the same message, different host. Thanks – dawg Jun 05 '13 at 05:13
14

The various functions in itertools (takewhile() comes to mind) can help.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358