Jean-François Fabre Jean-François Fabre - 1 year ago 56
Python Question

cleanest way to call one function on a list of items

In python 2, I used

to apply a function to several items, for instance, to remove all items matching a pattern:


Of course I ignore the return code of
, I just want all files to be deleted. It created a temp instance of a list for nothing, but it worked.

With Python 3, as
returns an iterator and not a list, the above code does nothing.
I found a workaround, since
, I use
to force iteration on the full list, without creating a
(better performance)


But it seems a bit hazardous, specially when applying it to methods that return something. Another way to do that with a one-liner and not create an unnecessary list?

Answer Source

The change from map() (and many other functions from 2.7 to 3.x) returning a generator instead of a list is a memory saving technique. For most cases, there is no performance penalty to writing out the loop more formally (it may even be preferred for readability).

I would provide an example, but @vaultah nailed it in the comments..

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download