# Lambda Expressions: The Anonymous Function

### Get the full rundown of the history of Lambda expression and an explanation of the mysterious anonymous function.

Join the DZone community and get the full member experience.

Join For FreeOf the many concepts that I’ve come across in Python, the one that seems to deprive me of the most sleep is this concept of anonymous functions, also known as Lambda expressions. There are so many questions that race through my mind when it’s time for bed. Like, “Why would a function need to be anonymous in the first place?”, “What is a lambda and from what rock did it come from?“, “How do I make it work?” and, "Why do I even care?” These are the questions that keep me up at night and I’m sure that you must be feeling the same.

Nobody understands us, but it’s ok, in this article we’ll answer these questions and more so that hopefully we can both get a good night’s rest.

**What Kind of Name Is Lambda?**

Interestingly enough, Lambda is actually the 11^{th} letter of the Greek alphabet (λ) in lower case which also happens to have a Greek numerical value of 30. The Latin character "L" and the Cyrillic "л" (pronounced "El") were also both derived from the lambda.

Okay, so what does that have to do with Python? Nothing, really; the symbol itself is insignificant. However, it did allow for an easy transition into the origin story.

**History of the Lambda Expression**

Lambda expressions as we know them are products of the Lambda Calculus which was invented by Princeton University mathematician Alonzo Church. In an attempt to address the notion of a function from a computational perspective, Church created what is known as the lambda calculus.

Without diving too deeply into the mathematical side of things, Church’s Lambda Calculus basically captured a functional notion of computation. From that system, the Lambda expression was born. If you’re curious and want to know more, Computerphile provides an excellent description on the Lambda Calculus.

In the world of computer science, Alan Turing was the inventor of the Turing machine, which captured a basic state-based model of computation. It so happened that Alonzo Church was the Ph.D. supervisor for Mr. Turing. Now, although Church’s system was functional-based while Turing’s was state-based, both of these systems turned out to be equivalent thus leading to the Church-Turing Thesis. The Stanford Library goes in-depth into the background and details of the Church-Turing Thesis.

As a side note if you're curious as to why Mr. Church decided to use the notation “λ” over any other symbol. He stated clearly that it came from the notation “ˆx” used for class-abstraction by Whitehead and Russell, by first modifying “ˆx” to “∧x” to distinguish function-abstraction from class-abstraction, and then changing “∧” to “λ” for ease of printing. On the other hand, in his later years Church told two enquirers that the choice was more accidental: a symbol was needed and “λ” just happened to be chosen.

If none of that made sense to you then don’t worry we’re pretty much done with the boring stuff. So anyway...

**What’s the Point of Anonymous Functions?**

In Python, there are functions that have no name yet have the capacity to perform just as any other function. They are functions not bound to any identifier. These nameless functions otherwise known as anonymous functions are typically referred to as Lambda Expressions. These Lambda Expressions 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.

When a function is used only once or at least a limited amount of times in your program, you as the developer can benefit from their use. We’ll explore key differences between these lambda expressions and regular functions later but first let’s look at an example.

```
>>> def getSquare(num):
... return num**2
>>> getSquare(5)
25
```

We define a basic function that squares any number passed as an argument.

```
>>> getSquare = lambda x:x**2
>>> getSquare(5)
25
```

Using a lambda expression we can accomplish most tasks in a single line.

## How to Call a Lambda Expression

In order to define a lambda expression we do the following:

First, start the expression with the keyword `lambda`

. This tells Python that the expression that follows is a lambda function. Then follow the keyword with a colon and a return function. A good way to read our getSquare function is as such:

"Lambda x such that x is raised to the power of 2" (or x^{2 }to be precise).

It’s important to note that had we not bind our lambda function to the variable `getSquare`

we would receive an object like so.

```
>>> lambda x:x**2
<function <lambda> at 0x002C0810>
```

These objects save a considerable amount of space. Additionally, we have to pass in the argument in order to execute the expression. In other words, our number 5 serves as the variable x in our expression.

Let’s look at another example:

```
>>> random_list = [2,4,5,6,8,7,9,10,13,25,43]
>>> res = list(filter(lambda x: (x%2 ==0),random_list))
>>> res
[2, 4, 6, 8, 10]
```

We define a random sequence of numbers. Using the lambda function combined with the filter method we are able to extract all of the even numbers. This expression can be easily modified by making one small change.

```
>>> res = list(filter(lambda x: (x%2 !=0),random_list))
>>> res
[5, 7, 9, 13, 25, 43]
```

Hopefully, you’re beginning to see the potential in using these anonymous functions. So far we’ve only been passing in one variable into our lambda expressions. Let’s look at how we can implement a second variable.

```
>>> full_name = lambda fn, ln: f'{fn.strip().title()} {ln.strip().title()}'
>>> full_name(' haNs ','SOLO ')
'Hans Solo'
```

In this example, we create an anonymous function that takes two inputs, a first name and a last name. The function will strip any excess spaces within the string and convert all characters to lower case with the exception of the first character. By using the f-string we include a space between the two without having to physically include it.

At this point, you’re probably wondering why you don’t use them all the time. The answer is quite simple really.

**Lambda Expressions vs. Regular Functions**

Lambda expressions are not a requirement. As the stellar software developers that we’ve come to be, we can make due just fine without them. In most cases, if the function is fairly simple and/or it will only be used a limited amount of times, using a lambda expression can significantly clean up our code and allow for ease of reading.

Technically, we can do without Regular Functions as well although that would be a syntactic nightmare. If our program has bits of code that is used repetitively then implementing a function(that is giving it a name and calling it) among those various locations would be the smart choice.

Now if there is a need for a function that won’t be needed more than once we can define in place and call it while it remains nameless. At this point, it’s important to note that a lambda expression can hold only one expression, therefore the expression has to be short.

At this point, we can start talking about functions that create functions also known as higher-order functions. Consider the following example from Socratica.

```
>>> def build_quadratic_function(a, b, c):
... """Returns the function f(x) = ax^2 + bx +c"""
... return lambda x: a*x**2 + b*x + c
>>> f = build_quadratic_function(2,3,-5)
>>> f(0)
-5
>>> f(5)
60
```

We define a function that returns a lambda expression. Then we create the function 2x^{2 }+ 3x -5 using the inputs. By testing it against 0 we get -5. Likewise, by testing our function against 5 our result is 60.

If we wanted to, we could call our function in a single line like so.

```
>>> build_quadratic_function(3,0,1)(2)
13
```

**Conclusion**

While having a single line may be convenient it’s important to consider the readability of our code. Sometimes having an extra line or two can prove to be more beneficial than displaying code in one line, especially when collaborating with others.

At this point, you should have a solid understanding of the origin of the lambda expression and the term anonymous functions, appropriate use scenarios, as well as how to properly implement them. If you enjoyed this article check out my article How to Check for Anagrams in Python Using Counter. Please take a moment to share and leave a comment. Don’t forget to follow me on social media. Until next time. Happy Coding!

Published at DZone with permission of Leaundrae Mckinney. See the original article here.

Opinions expressed by DZone contributors are their own.

Comments