I need to do something that is functionally equivalent to this:
for foo in foos: bar = foo.get_bar() # Do something with bar
My first instinct was to use map
, but this did not work:
for bar in map(get_bar, foos): # Do something with bar
Is what I'm trying to accomplish possible with map
? Do I need to use a list comprehension instead? What is the most Pythonic idiom for this?
Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.
Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc.
To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.
map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)
Either with lambda
:
for bar in map(lambda foo: foo.get_bar(), foos):
Or simply with instance method reference on your instance's class:
for bar in map(Foo.get_bar, foos):
As this was added from a comment, I would like to note that this requires the items of foos
to be instances of Foo
(i.e. all(isinstance(foo, Foo) for foo in foos)
must be true) and not only as the other options do instances of classes with a get_bar
method. This alone might be reason enough to not include it here.
Or with methodcaller
:
import operator get_bar = operator.methodcaller('get_bar') for bar in map(get_bar, foos):
Or with a generator expression:
for bar in (foo.get_bar() for foo in foos):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With