Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using while in list comprehension or generator expressions

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.

like image 397
highBandWidth Avatar asked Mar 31 '11 20:03

highBandWidth


People also ask

Can while be used in list comprehension?

No, you cannot use while in a list comprehension.

What is the difference between a list comprehension dict comprehension and generator expression?

The only difference between Generator Comprehension and List Comprehension is that the former uses parentheses.

Is a list comprehension a generator?

List comprehensions and generators are not different at all; they are just different ways of writing the same thing. A list comprehension produces a list as output, a generator produces a generator object.

Which is faster list comprehension or generator expression?

Thus, generator expressions are faster than list comprehension and hence time efficient.


2 Answers

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.

like image 121
dawg Avatar answered Oct 17 '22 05:10

dawg


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

like image 41
Ignacio Vazquez-Abrams Avatar answered Oct 17 '22 04:10

Ignacio Vazquez-Abrams