filter in for loop

Jerry Hill malaclypse2 at
Thu Aug 28 17:12:47 CEST 2008

On Thu, Aug 28, 2008 at 6:20 AM, GHZ <geraint.williams at> wrote:
> is there a shortcut I'm missing?

Well, there's another way to do it, using the filter built in function:

for filename in filter(lambda f:f.endswith('.xml'), os.listdir('.')):
	print filename

You can do the same thing with itertools.ifilter if you need to deal
with arbitrary iterables.  I think your first example of:

for filename in os.listdir('.'):
   if filename.endswith('.xml'):
       <do something>

Is the most readable though.


More information about the Python-list mailing list