Python Lambda Functions
Tags: python, lambda, programming, code
Published: 2021-01-02 00:13:17

---
canonical_url: https://kelvinmwinuka.com/python-lambda-functions-example/
---

Python lambda functions are an invaluable feature. One of the benefits of using Python is that it facilitates relatively compact code compared to other programming languages. This means getting so much more done with fewer lines of code.

<!-- wp:paragraph -->
<p>This isn't always the case, however. If you're not aware of the tools python provided in order to achieve this, it is very easy to write verbose code that defeats the point of picking Python for its "compactness".</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>One such tool is the lambda function. These allow us to create anonymous functions in python. If you've read good python programmers' code before, you might have come across something that looks like this:</p>
<!-- /wp:paragraph -->

```python
add = lambda a,b : a + b
```

The code above might look a bit confusing, let me clarify the syntax of a lambda function by breaking it down into its components. Lambda functions have 3 components: the 'lambda' keyword (of course), the set of arguments, and an expression.

```python
lambda [(optional) arguments] : [expression]
```

<!-- wp:heading {"level":3} -->
<h3>The Rules</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Before we go into detail about the implementation of lambda functions, let's first discuss their rules:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>Lambda functions are nameless (unless assigned to a variable). You cannot assign a function name after the 'lambda' keyword' as you would with the 'def' keyword.</li><li>Arguments are optional. Lambda functions can be defined without passing any arguments, just like a regular function.</li><li>Lambda functions can only have one expression.</li><li>Just like a regular function, you can return anything from a lambda function. It is also possible to return nothing.</li><li>Lambda functions can be assigned to variables for repeated use. This is the only way to name a lambda function.</li><li>Lambda functions can be returned from regular functions.</li><li>Lambda functions can return other lambda functions.</li></ol>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Why Use Lambda Functions?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>If you have never used lambda functions before, you probably think that you would do just fine without them, and you'd be right. However, as I've stated before, they play an important role in making sure we maintain clean, compact and pythonic code.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Lambda functions are most useful in situations where an anonymous function is required for single-use or repeated use.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Implementation</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>As stated before, we can use lambda functions alongside regular functions to generate functions. Let's create an example where we want to create 3 functions. One that doubles a given number, one that triples a given number, and one that quadruples a given number. We could achieve this by creating 3 different functions:</p>
<!-- /wp:paragraph -->

```python
def doubler(n):
    return n * 2

def tripler(n):
    return n * 3

def quadroupler(n):
    return n * 4
```

Instead of writing the code above, we could create a function that returns a lambda function with the functionality that we want:

```python
def function_generator(n):
    return lambda a : a * n
```

Now we create our desired functions:

```python
doubler = function_generator(2)
tripler = function_generator(3)
quadroupler = function_generator(4)
```

The function_generator function returns a function that will multiply its argument to whatever argument was passed to function_generator. We can test this with the following statement:

```python
print(doubler(4), tripler(4), quadroupler(4)) # Output 8 12 16
```

```python
function_generator = lambda n : lambda a : a * n
```

<!-- wp:paragraph -->
<p>The previous test line should produce the same output as before.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Remember that a lambda function assigned to a variable makes the variable callable as a function. When introducing the topic, I gave the following example:</p>
<!-- /wp:paragraph -->

```python
add = lambda a,b : a + b
```

This makes 'add' callable. So to add 2 numbers, we would use the following statement:

```python
add(4, 6) # Returns 10
```

<!-- wp:paragraph -->
<p>This also applies to functions returning lambdas. As long as a lambda function is returned, it is callable, no matter how deep the nesting goes. The function returned also has no name (hence 'anonymous') unless it is assigned to a variable.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We can also call a lambda function immediately after its definition:</p>
<!-- /wp:paragraph -->

```python
(lambda x : x * 2)(4) # Returns 8
```

<!-- wp:paragraph -->
<p>Make sure to store/print the value returned as it will not be accessible again later on in your module code. This format is very useful for list comprehensions. Suppose we have a list of numbers (nums) and we want to generate a new list of numbers such that for each number n in nums, n * 2 &gt; 50 should return True. How can we achieve this? </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Using a regular function and list comprehension:</p>
<!-- /wp:paragraph -->

```python
def validate(n):
    return n * 2 > 50

nums = [3, 1, 4, 22, 45, 1, 245, 6, 34, 4, 8, 14]
nums2 = [n for n in nums if validate(n)] # Returns [45, 245, 34]
```

However, we could eliminate the function definition altogether and include the validation expression within the list comprehension:

```python
nums = [3, 1, 4, 22, 45, 1, 245, 6, 34, 4, 8, 14]
nums2 = [n for n in nums if (lambda x : x * 2 > 50)(n)] # Returns [45, 245, 34]
```

Using Python lambda functions makes our code much more compact than in the previous example.

The post [Python Lambda Functions](https://kelvinmwinuka.com/python-lambda-functions-example/) appeared first on [Kelvin Mwinuka](https://kelvinmwinuka.com).

If you enjoyed this article, consider following my [website](https://kelvinmwinuka.com) for early access to my content before it gets published here (don’t worry, it’s still free with no annoying pop-up ads!). Also, feel free to comment on this post. I’d love to hear your thoughts!