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.
You can map operator symbols to those functions to retrieve the proper function, then assign it to your op variable and compute op(a, b).
Python List also includes the * operator, which allows you to create a new list with the elements repeated the specified number of times.
The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.
Creating Lists in Python You can use the in-built list() function to convert another data type into a list. It can also create an empty list without parameters.
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 expressionx+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)
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