Half-baked idea: list comprehensions with "while"

John O'Hagan research at johnohagan.com
Fri Apr 27 08:17:09 EDT 2012


On Fri, 27 Apr 2012 19:57:31 +1000
Chris Angelico <rosuav at gmail.com> wrote:

> On Fri, Apr 27, 2012 at 7:49 PM, Miles Rout <miles.rout at gmail.com> wrote:
> > We have if inside list comprehensions? I didn't know that, could you provide
> > an example?
> 
> You mean like:
> 
> [x*2+1 for x in range(10) if x%3]
> 

Speaking of list comprehensions, if clauses and half-baked ideas, sometimes I'd
like to be able to do something like:

results = [x = expensive_call(i) for i in iterable if condition(x)]

(or maybe "expensive_call(i) as x..." or whatever), instead of: 

results = []
for i in iterable:
    x = expensive_call(i)
    if condition(x):
        results.append(x)
--
John





More information about the Python-list mailing list