4 ms·
Yes but lambda allows some versatility, for example (excuse my Python, it is a bit rusty): formulas = { 'sum': lambda x,y: x+y, 'subst': la
by flavio81 9y ago
Yes but lambda allows some versatility, for example (excuse my Python, it is a bit rusty):
formulas = {
'sum': lambda x,y: x+y,
'subst': lambda x,y: x-y,
'mult': lambda x,y: x*y,
'pow': lambda x,y: x**y
}
def apply_operator(operation_name, x, y):
operation=formulas[operation_name]
return operation(x,y)
Using "def"s there would kill readability and easiness of coding.
- tobik 9y agoBad example :) Most simple uses of lambda like this can be substituted with functions from the operator module: import operator formulas = { 'sum': operator.add, 'subst': operator.sub, 'mult': operator.mul, 'pow': operator.pow }
- flavio81 9y agoI thank you for this example. If the operator definitions are not trivial and you want to keep them well mantained, then your example is very good. However, what I meant was that for fast, quick coding, if your 'operator' function is really simple, then lambda fints perfectlu. I know the Zen of Python says: "There should be one—and preferably only one—obvious way to do it", but i don't align to that principle. I think there should be more than one way to do something, and one should choose one that fits the best.