I have a list of objects and they have a method called process. In Python 2 one could do this
map(lambda x: x.process, my_object_list)
In Python 3 this will not work because map doesn't call the function until the iterable is traversed. One could do this:
list(map(lambda x: x.process(), my_object_list))
But then you waste memory with a throwaway list (an issue if the list is big). I could also use a 2-line explicit loop. But this pattern is so common for me that I don't want to, or think I should need to, write a loop every time.
Is there a more idiomatic way to do this in Python 3?
x
's type isX
, thenmap(X.process, list_of_objects)
will work just fine"In Python 3... map doesn't call the function until the iterable is traversed."
Followed by:"But then you waste memory with a throwaway list..."
Just want to make sure you do understand that in Python 2, the thrown awaylist
is still the case. The switch to an iterator in 3 is a great improvement. At any rate: just use a for loop. There is no superior idiom.