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

Andreas Nilsson adde at trialcode.com
Fri Oct 3 13:17:53 CEST 2008

I'm reposting this here after erroneously posting it on python-dev.

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):

Stupid idea? Am I missing some obviously better way of achieving the  
same result?


More information about the Python-ideas mailing list