For loop comprehensions

Steven D'Aprano steve+comp.lang.python at
Fri Feb 11 21:34:02 EST 2011

On Fri, 11 Feb 2011 16:59:52 -0700, Ian Kelly wrote:

> Why not allow the same thing in for-loop conditions?  

Because new syntax and new language features means more work. Somebody 
has to write the code, make sure that it doesn't break existing Python 
code, test it for bugs, change the documentation, write regression tests 
for it... And then, having done it for CPython, somebody else has to do 
the same for IronPython, Jython, PyPy, CLPython, Stackless ... And all 
that code has to be maintained.

Because new syntax and features increases the size and complexity of the 
Python code base, which means more bugs and more tests needed.

Because new syntax and features increases the size and complexity of the 
documentation needed, and hence increases the amount of things that need 
to be learned.

Because the guiding philosophy of Python is "there should be one, and 
preferably only one, obvious way to do it". That doesn't mean that 
multiple ways of doing it are forbidden (far from it!) but it does mean 
that Python is conservative about adding multiple ways of spelling the 
same thing.

New features don't come for free. They have costs too. You need something 
more than just "why not" to justify adding features -- you also need a 
"why" as well.

So... why add extra syntax to for loops when they're already very simple 
and effective? 

There's nothing wrong with writing

for x in iterable:
    if condition(x):

The existing syntax is clear and obvious. There's no clear benefit to 
shifting the if clause to the for expression: it complicates the parser, 
and any benefit (if any!) only applies to a tiny fraction of for loops. 
You save one line, which is trivial. You may save one indentation level, 
which might, sometimes, be useful, but more often will also be trivial. 
If there's an advantage to the suggestion, it's small.

> I think that
> anything that makes the language syntax more consistent is good.

"A foolish consistency is the hobgoblin of little minds."

Consistency, in and of itself, is not a virtue.


More information about the Python-list mailing list