It is understood that Python lambda functions help in creating anonymous functions. These can be used in other functions like map(), reduce(), filter() and key() in sorting functions. It can also be used to demonstrate and utilise lexical closures. What I would like to specifically know here is, do lambda functions have a specific advantage over regular functions in terms of their execution times, considering all other factors to be unchanged? As I am new to Python, I have tried to understand them by analogously comparing them with the inline functions of C++. Inline functions, as I understand from C++, are useful in saving time as they do not require the necessary "housekeeping tasks" concerned with context switching that occur during function calls and jumps. Do Python Lambda functions provide with such similar advantages over regular functions?
Thanks in advance!
No. The function objects generated by
lambda behave exactly like those generated by
def. They do not execute any faster. (Also,
inline in modern C++ is no longer a directive telling the compiler to inline a function, and has very little to do with inlining.)
If you want, you can take a look at the bytecode disassembly for a
lambda and an equivalent
import dis dis.dis(lambda x: x + 2) print() def f(x): return x + 2 dis.dis(f)
3 0 LOAD_FAST 0 (x) 3 LOAD_CONST 1 (2) 6 BINARY_ADD 7 RETURN_VALUE 6 0 LOAD_FAST 0 (x) 3 LOAD_CONST 1 (2) 6 BINARY_ADD 7 RETURN_VALUE
No difference. You can also time them:
import timeit def f(x): return x + 2 g = lambda x: x + 2 print(timeit.timeit('f(3)', globals=globals())) print(timeit.timeit('g(3)', globals=globals()))
The lambda actually took longer in this run.
Before you ask, no,
lambda has no performance disadvantage over
def either. The winner of the above race is basically up to luck.
def do have a significant disadvantage over avoiding the use of a callback function entirely, though. For example,
lambda has a significant performance penalty relative to list comprehensions:
import timeit print(timeit.timeit('list(map(lambda x: x*x, range(10)))')) print(timeit.timeit('[x*x for x in range(10)]'))
def, Python functions are expensive to call.