7

The reason I ask is pure curiosity. I could see, possibly, that this might be useful if you didn't know ahead of time what operations you wanted to apply to certain variables, or to apply a different operation during a certain level in a recursive call, or perhaps it may just make certain things easier and/or neater.

Though am just speculating, it could be a really bad idea, but overall am just curious.

Jim Jam
  • 713
  • 4
  • 10
  • 22

2 Answers2

12

You may use operator module.

The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y. The function names are those used for special class methods; variants without leading and trailing __ are also provided for convenience.

So storing "operation" in list is as simple as:

import operator
operations = [operator.add, operator.sub]
# add two numbers
s = operations[0](1, 2)
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
0

Yes you can put functions in a list, or a dict (which can be quite useful), you can do it with functions declared with def, lambdas or import already defined functions, from operators module with your examples (operator.add, etc)

polku
  • 1,575
  • 2
  • 14
  • 11