[ x for x in xrange(10) when p(x) ]

Leif K-Brooks eurleif at ecritters.biz
Thu Nov 10 06:18:49 EST 2005


bonono at gmail.com wrote:
> Leif K-Brooks wrote:
> 
>>bonono at gmail.com wrote:
>>
>>>thanks. that is what I am doing now, in a more generic form :
>>>
>>>takewhile(p, (x for x in xrange(100000000)))
>>
>>How does a useless generator expression make it more generic?
> 
> xrange is only picked as an example. I may be newbie on python but not
> that dumb if all I want is a list of integer(sorted) that meets certain
> criteria.
> 
> takewhile(p, (x for x in
> some_function_that_could_potentially_generate_a_long_list_of_elements_but_first_element_that_meets_the_condition_can_come_fast(*args,**kwargs)))

Wrapping a function in a generator expression doesn't magically make it
  lazily evaluated. The whole list has to be generated and returned;
using a generator expression instead of a list comprehension just means
that it doesn't need to be copied in memory.



More information about the Python-list mailing list