1

I would like to know if there's a function similar to map but working for methods of an instance. To make it clear, I know that map works as:

map( function_name , elements )
# is the same thing as:
[ function_name( element ) for element in elements ]

and now I'm looking for some kind of map2 that does:

map2( elements , method_name )
# doing the same as:
[ element.method_name() for element in elements ]

which I tried to create by myself doing:

def map2( elements , method_name ):
    return [ element.method_name() for element in elements ]

but it doesn't work, python says:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'method_name' is not defined

even though I'm sure the classes of the elements I'm working with have this method defined.

Does anyone knows how could I proceed?

2 Answers 2

4

operator.methodcaller() will give you a function that you can use for this.

map(operator.methodcaller('method_name'), sequence)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Just adding that one might import operator before
1

You can use lambda expression. For example

a = ["Abc", "ddEEf", "gHI"]
print map(lambda x:x.lower(), a)

You will find that all elements of a have been turned into lower case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.