2

I'm developing a bunch of functions that have the same basic structure - they take two lists and use a loop to do a particular operation pairwise for the two lists (for example, one will take each element of a list raised to the power represented by the corresponding element in the second list).

Since all of these function differ only by an operator, I was wondering - is it possible to set a variable to an operator? For example, can you do (something similar to):

var = +
var2 = 5 var 7       #var2 is now 12

I know that specifically doesn't work, but is there anything similar that does work similarly?

0

2 Answers 2

7

Yes! You want the operator module, which "exposes Python's intrinsic operators as efficient functions."

import operator

op = operator.add
var = op(5, 7)

As @falsetru points out, a lambda is handy too; the functions in operator are going to be a wee bit faster, though:

from timeit import timeit
print timeit("add(5, 7)", "add = lambda x, y: x+y")    # about 0.176 OMM
print timeit("add(5, 7)", "from operator import add")  # about 0.136 OMM
Sign up to request clarification or add additional context in comments.

Comments

2

Try following:

>>> op = lambda a, b: a + b
>>> result = op(5, 7)
>>> result
12

3 Comments

@KevinMills, You can use abitrary expression inside the lambda body (lambda a, b: (a+b)*2). But as @kindall mentioned, if you do simply adding, operator.add is more concise and maybe faster.
Is this better than simply defining and passing a subfunction?
@KevinMills, You have to define a function if you have multiple statements to execute. If there's only one expression, there's no difference. You can check it by import dis; dis.dis(lambda a, b: a + b). ; So it's your preference which one you use. See ideone.com/AHc6JQ

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.