Python Lambda λ

If you are like me who have a few months experience of Python, then you might be in the same position as me — know something about Python, but not enough. So I spent sometime to gather bits and pieces of scattered knowledge to dig deeper into Python. In this blog, the piece will be lamda.

In computer programming, an anonymous function (lambda expression) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions, or used for constructing the result of a higher-order function that needs to return a function.

If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

— wiki

Lambda — a Comparison

A Lambda Function in Python programming is an anonymous function. This is nothing new, as there’s also something similar in JavaScript.

In JavaScript pre-ES6 we have function expressions as anonymous function.

function (a, b) { return a + b };

In ES6 there is arrow functions.

(a, b) => a + b;

We can invoke them directly in Immediately Invoked Function Expressions (IIFE) like:

(function (a, b) {return a + b })(1, 2); // 3((a,b) => (a+b))(1, 2); // 3

But since in arrow functions there is no bound this , it means we cannot bind the enclosing lexical scope to it:

window.age = 10; 
function Person() {
this.age = 42;
setTimeout(() => {
// <-- Arrow function executing in an instance of Person scope
console.log("this.age", this.age);
// yields "42" because the function executes on the Person scope
}, 100);

var p = new Person();

But how about in Python?

Syntax and Basic Examples

Every anonymous function in Python will have 3 parts:

  • The lambda keyword;
  • The parameters;
  • The function body

A lambda function can have multiple parameters, but the function body can only contain one expression that is written in one line of code.

lambda p1, p2: expression

Since in Python, functions are first-class objects meaning we can pass functions as arguments to other functions or assign them to variables. This is what we can do with lamda.

Example 1: assign to variableadd = lambda x, y: x + y
print (add (1, 2))
Example 2: validate as lamdaadd = lambda x, y: x + y
<function <lambda> at 0x103c23200>
Example 3: IIFE(lambda x, y : x+y)(1,2)

Because Python supports functions as first-class objects and that lamda is also a paradigm of functional programming, we can combine the two to generate very sweet outcome. In such cases, using lambdas offer an elegant way to create a one-time function without writing complex syntax.

arr = [9,13,24,5,63,35,87,42]
filtered_result = filter (lambda x: x > 20, arr)
map_result = map (lambda x: x*x, arr) sum_result = reduce(lambda x, y: x + y, arr)

Another common example is to manipulate the default `key` argument in some built-in functions like sorted. This key function is used to compute a comparison key when determining the sorting order.

>>> alpha = ["B", "c", "D", "a", "e"] 
>>> sorted(alpha, key=lambda s: s.casefold())
['a', 'B', 'c', 'D', 'e']

A Verdict

Lamda is nice and convenient. But using lamda has some gotchas.

  • Python discourages writing complicated lambda functions, so you don’t confuse yourself or your fellow colleagues.
  • Lambda functions can only have one expression in their body.
  • Lambda function can’t contain any statements such as return, pass, assert, or raise .
  • Lambdas do not have a name associated with them (remember the <function <lambda> at 0x103c23200>) So if you want reusable component, use normal functions.
  • At the byte-code level, there is not really differences between lambdas and normal functions.

That’s so much of it today!

Happy Reading!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store