[Python-Dev] if-syntax for regular for-loops

David Gowers 00ai99 at gmail.com
Fri Oct 3 12:35:12 CEST 2008


Hi Andreas,

On Fri, Oct 3, 2008 at 7:40 PM, Andreas Nilsson <adde at trialcode.com> wrote:
> Hi.
> First post so here it goes.
> My name is Adde, and I'm a Swedish software developer. I've been programming
> for about 23 years now since starting with Basic on the C64. I've been
> through most well known and a couple of lesser known languages in search of
> the perfect one. At the moment I'm writing a custom ctypes interface to the
> Firebird database (need access to advanced features, portability to Windows
> and I definitely don't enjoy setting up GCC on Windows).
> I've programmed a lot of C/C++ in my days so I thought I'd at least join the
> list and see if anything piques my interest enough to dive in.
>
> With that out of the way, on to todays subject:
> I use list comprehensions and generator expressions a lot and lately I've
> found myself writing a lot of code like this:
>
> for i in items if i.some_field == some_value: i.do_something()
>
> Naturally it won't work but it seems like a pretty straight-forward
> extension to allow compressing simple loops to fit on one line. The
> alternative, in my eyes, suggests there's something more happening than a
> simple include-test which makes it harder to comprehend.
>
> for i in items:
>        if i.some_field == some_value: i.do_something()
>
> One possibility of course is to use a generator-expression but that makes it
> look like there are two for loops and it feels like a waste setting up a
> generator just for filtering.
>
> for i in (i for i in items if some_field == some_value):
>        i.do_something()
>
> Stupid idea? Am I missing some obviously better way of achieving the same
> result?

List comprehension.


[i.do_something() for i in items if i.some_field == some_value]


With the restriction that the statement you use must seem to return an
expression..
For example


[print(i) for i in range(9) if i % 2]


Fails with SyntaxError, whereas


def f(v):
    print (v)
[f(i) for i in range(9) if i % 2]


correctly prints

1
3
5
7

HTH,
David

-- 
Everything has reasons. Nothing has justification.
Ĉio havas kialojn; Neniaĵo havas pravigeron.


More information about the Python-Dev mailing list