Can Anyone explain which is faster? What are the advantages or disadvantages of using lambda?
Asked
Active
Viewed 1,617 times
0
-
It's a shortcut for writing function. Execution will be almost same. – Rahul Jun 30 '17 at 06:38
-
Only use lambda for *anonymous functions*, for example, like a key function to pass to `sorted()` – Chris_Rands Jun 30 '17 at 08:07
1 Answers
1
Let's create very simple functions; one as a normal Python function and one using lambda.
# Lambda Function
foo = lambda x: x
# Normal Python function
def bar(x):
return x
Now compare the execution time of both the functions using timeit
module:
>>> import timeit
# `timeit` measurement of Lambda function
>>> timeit.timeit("foo(123)", setup="from __main__ import foo")
0.0789480209350586
# `timeit` measurement of Normal Python function
>>> timeit.timeit("bar(123)", setup="from __main__ import bar")
0.07846808433532715
As you see, execution time of both the function is almost same.

Moinuddin Quadri
- 46,825
- 13
- 96
- 126