Half-baked idea: list comprehensions with "while"

Kiuhnm kiuhnm03.4t.yahoo.it
Fri Apr 27 06:56:04 EDT 2012


On 4/27/2012 11:49, Miles Rout wrote:
> On 27/04/2012 5:57 a.m., Kiuhnm wrote:
>> On 4/26/2012 19:48, Paul Rubin wrote:
>>> Roy Smith<roy at panix.com> writes:
>>>> x = [a for a in iterable while a]
>>>
>>> from itertools import takewhile
>>>
>>> x = takewhile(bool, a)
>>
>> I see that as a 'temporary' solution, otherwise we wouldn't need 'if'
>> inside of list comprehensions either.
>>
>> Kiuhnm
>
> We have if inside list comprehensions? I didn't know that, could you
> provide an example?

elems = [4, 1, 9, 6, 3, 8, 3, 9, 2]
small_elems = [x for x in elems if x < 5]
print str(small_elems)          # 4, 1, 3, 3, 2

#leading_small_elems = [x for x in elems while x < 5]
#print str(leading_small_elems)     # 4, 1

Kiuhnm



More information about the Python-list mailing list