Do Python lambda functions help in reducing the execution times?











up vote
22
down vote

favorite
1












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 the 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?



Some relevant posts that I found useful but not necessarily helpful for my question:
Why are Python lambdas useful?
Why use lambda functions?



Thanks in advance!










share|improve this question
























  • Yes if you just want to return something from the function you should prefer lambda.
    – Sharvin Shah
    Dec 1 at 8:00










  • Currently, accepting user2357112's answer until a better explanation is put forward. Thanks everyone!
    – bp14
    2 days ago

















up vote
22
down vote

favorite
1












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 the 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?



Some relevant posts that I found useful but not necessarily helpful for my question:
Why are Python lambdas useful?
Why use lambda functions?



Thanks in advance!










share|improve this question
























  • Yes if you just want to return something from the function you should prefer lambda.
    – Sharvin Shah
    Dec 1 at 8:00










  • Currently, accepting user2357112's answer until a better explanation is put forward. Thanks everyone!
    – bp14
    2 days ago















up vote
22
down vote

favorite
1









up vote
22
down vote

favorite
1






1





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 the 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?



Some relevant posts that I found useful but not necessarily helpful for my question:
Why are Python lambdas useful?
Why use lambda functions?



Thanks in advance!










share|improve this question















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 the 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?



Some relevant posts that I found useful but not necessarily helpful for my question:
Why are Python lambdas useful?
Why use lambda functions?



Thanks in advance!







python lambda






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday

























asked Dec 1 at 7:58









bp14

1156




1156












  • Yes if you just want to return something from the function you should prefer lambda.
    – Sharvin Shah
    Dec 1 at 8:00










  • Currently, accepting user2357112's answer until a better explanation is put forward. Thanks everyone!
    – bp14
    2 days ago




















  • Yes if you just want to return something from the function you should prefer lambda.
    – Sharvin Shah
    Dec 1 at 8:00










  • Currently, accepting user2357112's answer until a better explanation is put forward. Thanks everyone!
    – bp14
    2 days ago


















Yes if you just want to return something from the function you should prefer lambda.
– Sharvin Shah
Dec 1 at 8:00




Yes if you just want to return something from the function you should prefer lambda.
– Sharvin Shah
Dec 1 at 8:00












Currently, accepting user2357112's answer until a better explanation is put forward. Thanks everyone!
– bp14
2 days ago






Currently, accepting user2357112's answer until a better explanation is put forward. Thanks everyone!
– bp14
2 days ago














1 Answer
1






active

oldest

votes

















up vote
38
down vote



accepted










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 def:



import dis

dis.dis(lambda x: x + 2)

print()
def f(x): return x + 2

dis.dis(f)


Output:



  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()))


Output:



0.06977041810750961
0.07760106027126312


The lambda actually took longer in this run. (There seems to be some confusion in the comments about whether we're timing enough work to be meaningful. timeit wraps the timed statement in a million-iteration loop by default, so yes, we are.)



Before you ask, no, lambda has no performance disadvantage over def either. The winner of the above race is basically up to luck. lambda and def do have a significant disadvantage over avoiding the use of a callback function entirely, though. For example, map-with-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)]'))


Output:



1.5655903220176697
0.7803761437535286


Whether lambda or def, Python functions are expensive to call.






share|improve this answer



















  • 6




    "map-with-lambda has a significant performance penalty relative to list comprehensions". We don't say that enough
    – Jean-François Fabre
    Dec 1 at 8:36










  • @user2357112 Thanks for your reply. The bytecode disassembly and timing outputs are revealing. My current understanding is: lambdas are not particularly advantageous over def functions. They help to make the code more readable(if not always, at least sometimes). It is also a legacy of functional programming choices - Thanks!
    – bp14
    Dec 1 at 10:26






  • 1




    @Jean-FrançoisFabre: maybe, although just looking at the two lines of code side-by-side I prefer the list comprehension regardless of performance. So there's normally no need to talk about it!
    – Steve Jessop
    Dec 1 at 14:12












  • ok let me say it again :) list+map+lambda combination is there only for so-called experts to boast over how well they understand python, where list comprehensions are there only because they're easy to understand.
    – Jean-François Fabre
    Dec 1 at 14:14








  • 2




    @Jean-FrançoisFabre: agreed, and specifically I'd say that list+map+lambda is there to prove that there's something else (probably one or more functional languages) that you're more expert in than you are in Python.
    – Steve Jessop
    Dec 1 at 14:15











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53568926%2fdo-python-lambda-functions-help-in-reducing-the-execution-times%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
38
down vote



accepted










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 def:



import dis

dis.dis(lambda x: x + 2)

print()
def f(x): return x + 2

dis.dis(f)


Output:



  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()))


Output:



0.06977041810750961
0.07760106027126312


The lambda actually took longer in this run. (There seems to be some confusion in the comments about whether we're timing enough work to be meaningful. timeit wraps the timed statement in a million-iteration loop by default, so yes, we are.)



Before you ask, no, lambda has no performance disadvantage over def either. The winner of the above race is basically up to luck. lambda and def do have a significant disadvantage over avoiding the use of a callback function entirely, though. For example, map-with-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)]'))


Output:



1.5655903220176697
0.7803761437535286


Whether lambda or def, Python functions are expensive to call.






share|improve this answer



















  • 6




    "map-with-lambda has a significant performance penalty relative to list comprehensions". We don't say that enough
    – Jean-François Fabre
    Dec 1 at 8:36










  • @user2357112 Thanks for your reply. The bytecode disassembly and timing outputs are revealing. My current understanding is: lambdas are not particularly advantageous over def functions. They help to make the code more readable(if not always, at least sometimes). It is also a legacy of functional programming choices - Thanks!
    – bp14
    Dec 1 at 10:26






  • 1




    @Jean-FrançoisFabre: maybe, although just looking at the two lines of code side-by-side I prefer the list comprehension regardless of performance. So there's normally no need to talk about it!
    – Steve Jessop
    Dec 1 at 14:12












  • ok let me say it again :) list+map+lambda combination is there only for so-called experts to boast over how well they understand python, where list comprehensions are there only because they're easy to understand.
    – Jean-François Fabre
    Dec 1 at 14:14








  • 2




    @Jean-FrançoisFabre: agreed, and specifically I'd say that list+map+lambda is there to prove that there's something else (probably one or more functional languages) that you're more expert in than you are in Python.
    – Steve Jessop
    Dec 1 at 14:15















up vote
38
down vote



accepted










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 def:



import dis

dis.dis(lambda x: x + 2)

print()
def f(x): return x + 2

dis.dis(f)


Output:



  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()))


Output:



0.06977041810750961
0.07760106027126312


The lambda actually took longer in this run. (There seems to be some confusion in the comments about whether we're timing enough work to be meaningful. timeit wraps the timed statement in a million-iteration loop by default, so yes, we are.)



Before you ask, no, lambda has no performance disadvantage over def either. The winner of the above race is basically up to luck. lambda and def do have a significant disadvantage over avoiding the use of a callback function entirely, though. For example, map-with-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)]'))


Output:



1.5655903220176697
0.7803761437535286


Whether lambda or def, Python functions are expensive to call.






share|improve this answer



















  • 6




    "map-with-lambda has a significant performance penalty relative to list comprehensions". We don't say that enough
    – Jean-François Fabre
    Dec 1 at 8:36










  • @user2357112 Thanks for your reply. The bytecode disassembly and timing outputs are revealing. My current understanding is: lambdas are not particularly advantageous over def functions. They help to make the code more readable(if not always, at least sometimes). It is also a legacy of functional programming choices - Thanks!
    – bp14
    Dec 1 at 10:26






  • 1




    @Jean-FrançoisFabre: maybe, although just looking at the two lines of code side-by-side I prefer the list comprehension regardless of performance. So there's normally no need to talk about it!
    – Steve Jessop
    Dec 1 at 14:12












  • ok let me say it again :) list+map+lambda combination is there only for so-called experts to boast over how well they understand python, where list comprehensions are there only because they're easy to understand.
    – Jean-François Fabre
    Dec 1 at 14:14








  • 2




    @Jean-FrançoisFabre: agreed, and specifically I'd say that list+map+lambda is there to prove that there's something else (probably one or more functional languages) that you're more expert in than you are in Python.
    – Steve Jessop
    Dec 1 at 14:15













up vote
38
down vote



accepted







up vote
38
down vote



accepted






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 def:



import dis

dis.dis(lambda x: x + 2)

print()
def f(x): return x + 2

dis.dis(f)


Output:



  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()))


Output:



0.06977041810750961
0.07760106027126312


The lambda actually took longer in this run. (There seems to be some confusion in the comments about whether we're timing enough work to be meaningful. timeit wraps the timed statement in a million-iteration loop by default, so yes, we are.)



Before you ask, no, lambda has no performance disadvantage over def either. The winner of the above race is basically up to luck. lambda and def do have a significant disadvantage over avoiding the use of a callback function entirely, though. For example, map-with-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)]'))


Output:



1.5655903220176697
0.7803761437535286


Whether lambda or def, Python functions are expensive to call.






share|improve this answer














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 def:



import dis

dis.dis(lambda x: x + 2)

print()
def f(x): return x + 2

dis.dis(f)


Output:



  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()))


Output:



0.06977041810750961
0.07760106027126312


The lambda actually took longer in this run. (There seems to be some confusion in the comments about whether we're timing enough work to be meaningful. timeit wraps the timed statement in a million-iteration loop by default, so yes, we are.)



Before you ask, no, lambda has no performance disadvantage over def either. The winner of the above race is basically up to luck. lambda and def do have a significant disadvantage over avoiding the use of a callback function entirely, though. For example, map-with-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)]'))


Output:



1.5655903220176697
0.7803761437535286


Whether lambda or def, Python functions are expensive to call.







share|improve this answer














share|improve this answer



share|improve this answer








edited Dec 1 at 19:12

























answered Dec 1 at 8:01









user2357112

148k12155243




148k12155243








  • 6




    "map-with-lambda has a significant performance penalty relative to list comprehensions". We don't say that enough
    – Jean-François Fabre
    Dec 1 at 8:36










  • @user2357112 Thanks for your reply. The bytecode disassembly and timing outputs are revealing. My current understanding is: lambdas are not particularly advantageous over def functions. They help to make the code more readable(if not always, at least sometimes). It is also a legacy of functional programming choices - Thanks!
    – bp14
    Dec 1 at 10:26






  • 1




    @Jean-FrançoisFabre: maybe, although just looking at the two lines of code side-by-side I prefer the list comprehension regardless of performance. So there's normally no need to talk about it!
    – Steve Jessop
    Dec 1 at 14:12












  • ok let me say it again :) list+map+lambda combination is there only for so-called experts to boast over how well they understand python, where list comprehensions are there only because they're easy to understand.
    – Jean-François Fabre
    Dec 1 at 14:14








  • 2




    @Jean-FrançoisFabre: agreed, and specifically I'd say that list+map+lambda is there to prove that there's something else (probably one or more functional languages) that you're more expert in than you are in Python.
    – Steve Jessop
    Dec 1 at 14:15














  • 6




    "map-with-lambda has a significant performance penalty relative to list comprehensions". We don't say that enough
    – Jean-François Fabre
    Dec 1 at 8:36










  • @user2357112 Thanks for your reply. The bytecode disassembly and timing outputs are revealing. My current understanding is: lambdas are not particularly advantageous over def functions. They help to make the code more readable(if not always, at least sometimes). It is also a legacy of functional programming choices - Thanks!
    – bp14
    Dec 1 at 10:26






  • 1




    @Jean-FrançoisFabre: maybe, although just looking at the two lines of code side-by-side I prefer the list comprehension regardless of performance. So there's normally no need to talk about it!
    – Steve Jessop
    Dec 1 at 14:12












  • ok let me say it again :) list+map+lambda combination is there only for so-called experts to boast over how well they understand python, where list comprehensions are there only because they're easy to understand.
    – Jean-François Fabre
    Dec 1 at 14:14








  • 2




    @Jean-FrançoisFabre: agreed, and specifically I'd say that list+map+lambda is there to prove that there's something else (probably one or more functional languages) that you're more expert in than you are in Python.
    – Steve Jessop
    Dec 1 at 14:15








6




6




"map-with-lambda has a significant performance penalty relative to list comprehensions". We don't say that enough
– Jean-François Fabre
Dec 1 at 8:36




"map-with-lambda has a significant performance penalty relative to list comprehensions". We don't say that enough
– Jean-François Fabre
Dec 1 at 8:36












@user2357112 Thanks for your reply. The bytecode disassembly and timing outputs are revealing. My current understanding is: lambdas are not particularly advantageous over def functions. They help to make the code more readable(if not always, at least sometimes). It is also a legacy of functional programming choices - Thanks!
– bp14
Dec 1 at 10:26




@user2357112 Thanks for your reply. The bytecode disassembly and timing outputs are revealing. My current understanding is: lambdas are not particularly advantageous over def functions. They help to make the code more readable(if not always, at least sometimes). It is also a legacy of functional programming choices - Thanks!
– bp14
Dec 1 at 10:26




1




1




@Jean-FrançoisFabre: maybe, although just looking at the two lines of code side-by-side I prefer the list comprehension regardless of performance. So there's normally no need to talk about it!
– Steve Jessop
Dec 1 at 14:12






@Jean-FrançoisFabre: maybe, although just looking at the two lines of code side-by-side I prefer the list comprehension regardless of performance. So there's normally no need to talk about it!
– Steve Jessop
Dec 1 at 14:12














ok let me say it again :) list+map+lambda combination is there only for so-called experts to boast over how well they understand python, where list comprehensions are there only because they're easy to understand.
– Jean-François Fabre
Dec 1 at 14:14






ok let me say it again :) list+map+lambda combination is there only for so-called experts to boast over how well they understand python, where list comprehensions are there only because they're easy to understand.
– Jean-François Fabre
Dec 1 at 14:14






2




2




@Jean-FrançoisFabre: agreed, and specifically I'd say that list+map+lambda is there to prove that there's something else (probably one or more functional languages) that you're more expert in than you are in Python.
– Steve Jessop
Dec 1 at 14:15




@Jean-FrançoisFabre: agreed, and specifically I'd say that list+map+lambda is there to prove that there's something else (probably one or more functional languages) that you're more expert in than you are in Python.
– Steve Jessop
Dec 1 at 14:15


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53568926%2fdo-python-lambda-functions-help-in-reducing-the-execution-times%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Сан-Квентин

Алькесар

Josef Freinademetz