[Python-ideas] while conditional in list comprehension ??

Chris Angelico rosuav at gmail.com
Mon Jan 28 08:56:14 EST 2013


Argh, sorry folks. Hit the wrong list. :(

On Tue, Jan 29, 2013 at 12:55 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Tue, Jan 29, 2013 at 12:33 AM, Wolfgang Maier
> <wolfgang.maier at biologie.uni-freiburg.de> wrote:
>> Why not extend this filtering by allowing a while statement in addition to
>> if, as in:
>>
>> [n for n in range(1,1000) while n < 400]
>
> The time machine strikes again! Check out itertools.takewhile - it can
> do pretty much that:
>
> import itertools
> [n for n in itertools.takewhile(lambda n: n<400, range(1,1000))]
>
> It's not quite list comp notation, but it works.
>
>>>> [n for n in itertools.takewhile(lambda n: n<40, range(1,100))]
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
> 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
> 37, 38, 39]
>
> ChrisA



More information about the Python-list mailing list