[Python-Dev] for loop with if filter

Terry Reedy tjreedy at udel.edu
Sat Nov 17 00:31:12 CET 2007


"Gustavo Carneiro" <gjcarneiro at gmail.com> wrote in message 
news:a467ca4f0711160617p11564c05q8b2c59e87981c028 at mail.gmail.com...
|I am finding myself often doing for loops over a subset of a list, like:
|
|        for r in results:
|            if r.numNodes != numNodes:
|                continue
|            # do something with r

Why write it backwards?

for r in results:
  if r.numNodes == numNodes
    # do something with r

is the direct parallel with the below code.

| It would be nice if the plain for loop was as flexible as list
| comprehensions and allowed an optional if clause, like this:
|
|        for r in results if r.numNodes == numNodes:
|            # do something with r

Same as above with ':\n' deleted.  A trivial difference.
An optional if clause is *less* flexible than an optional if statement and 
block.

| Has this idea come up before?  Does anyone else like this idea?

Yes, and Guido rejected at that time.

tjr
 





More information about the Python-Dev mailing list