for <var> in <sequence> if <condition>

Dave Brueck dbrueck at edgix.com
Thu Oct 5 11:04:13 EDT 2000


The list comprehensions with if-conditions in 2.0 are nifty, but is there
any reason that the usual for-loops can't also support an if condition?

Ex - If I have read in a file and I want to iterate over lines that start
with 'y' (ignoring leading whitespace) I can do:

for line in [line for line in lines if line.strip().startswith('y')]
  doStuff(line)

Given a list of strings:

["", "blue", " yellow", "yes"]

it calls doStuff with ' yellow' and 'yes'

So is there any good reason why we can't enhance the for-loop to handle the
if-condition for me? ie-

for line in lines if line.strip.startswith('y'):
  doStuff(line)

Beggars-can-be-choosers'ly yrs,
Dave





More information about the Python-list mailing list