Lambda Functions in Python

What are Lambda Functions?


In Python, functions are objects: they can be assigned to variables, can be returned from other functions, stored in lists or dicts and passed as parameters for other functions. Consider, for example, the map() built-in function. Its syntax is map(function, iterable) and it is used to handily apply function to every element of iterable.

map() actually returns an iterator object. In practice, we cast the result as a list, tuple, set, dict, etc, whichever is more convenient.

Suppose that you want to square every term of a list using the map() function. In order to do that, we'll define a square() function and use it as parameter for map():

my_list = [1,2,3,4,5]
def square(x):
    return x**2

my_modified_list = list(map(square, my_list))
print(my_modified_list)
[1, 4, 9, 16, 25]


However, if the only use of our square() function is to create this list, it is cleaner to use a lambda function:

my_list = [1,2,3,4,5]
my_modified_list = list(map(lambda x: x**2, my_list))
print(my_modified_list)
[1, 4, 9, 16, 25]

In Python, lambda functions are anonymous functions that take their name and syntax from Alonzo Church's Lambda calculus. Their syntax is:

lambda x_1,..., x_n : expression(x_1, ..., x_n)

This creates an anonymous function that receives as input the variables x_1, ..., x_n and returns the evaluated expression(x_1, ..., x_n).

The purpose of lambda functions is to be used as parameters for functions that accept functions as parameters, as we did with map() above. Python allows you to assign a lambda function to a variable, but the PEP 8 style guide advises against it. If you want to assign a simple function to a variable, it is better to do it as a one-line definition. This ensures the resulting object is properly named, improving traceback readability:

anonymous_square = lambda x : x**2def named_square(x): return x**2print(anonymous_square.__name__)
print(named_square.__name__)

# Works even if you reassign the functions
a = anonymous_square
b = named_square
print(a.__name__)
print(b.__name__)

Why Use Lambda Functions?

After the last paragraph, you might be wondering why you would want to use a lambda function. After all, anything that can be done with a lambda function could be done with a named function.

The answer to this is that the lambda function's purpose is to live inside larger expressions representing a computation. One way to think about this is by analogy with variables and values. Consider the following code:

x = 2

The variable x is a placeholder (or a name) for the integer 2. For instance, calling print(x) and print(2) gives exactly the same output. In the case of functions:

def square(x): return x**2

The function square() is a placeholder for the computation of squaring a number. This computation can be written in a nameless way as lambda x: x**2.

Following this philosophical digression, let's see some examples of applications for lambda functions.

Using Lambda with the sorted() Function

The sorted() function sorts an iterable. It accepts a function as its key argument, and the result of the function applied to each element of the iterable is used to order the elements.

This is perfectly suited to a lambda function: by setting the key parameter with a lambda function, we can sort by any kind of attribute of the elements. For example, we can sort a list of names by surname:

name_list = ['Grace Hopper', 'Ada Lovelace', 'Emmy Noether', 'Marie Curie']
​
sorted_by_surname = sorted(name_list, key = lambda x: x.split()[1])
​
print(sorted_by_surname)
['Marie Curie', 'Grace Hopper', 'Ada Lovelace', 'Emmy Noether']

Using Lambda with 'filter()' Function

The filter() function has the following syntax: filter(function, iterable) and it outputs the elements of iterable which evaluate function(element) as true (it is similar to an WHERE clause in SQL). We can use lambda functions as parameters for filter() to select elements from an iterable.

Consider the following example:

num_list = list(range(0,100))
​
multiples_of_15= filter(lambda x: (x % 3 == 0) and (x % 5 == 0), num_list)
​
print(list(multiples_of_15))
[0, 15, 30, 45, 60, 75, 90]

filter() applies the lambda function lambda x: (x % 3 == 0) and (x % 5 == 0) to each element of range(0,100), and returns a filter object. We access the elements by casting it as list.

Using Lambda with The map() Function


Our last example is something we've seen in the introduction - the map() function. The map() function syntax is: map(function, iterable), and map() applies function to each element of iterable, returning a map object that can be accessed by casting to a list.

We've seen how this can be applied to lists, but it could be applied to dicts using the dict.items() method:

my_data = {'Mary':1, 'Alice':2, 'Bob':0}
map_obj = map(lambda x: f'{x[0]} had {x[1]} little lamb', my_data.items())
print(', '.join((map_obj)))
Mary had 1 little lamb, Alice had 2 little lamb, Bob had 0 little lamb

or to a string:

my_string = 'abcdefg'
''.join(map(lambda x: chr(ord(x)+2),my_string))
'cdefghi'
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

We can use the map() function in ingenious ways - one example is applying many functions to the same input.

For example, suppose you are making an API that receives a text string, and you want to apply a list of functions to it.

Each function extracts some feature from the text. The features we want to extract are the number of words, the second word and the fourth letter of the fourth word:

def number_of_words(text):
  return len(text.split())
​
def second_word(text):
  return text.split()[1]
​
def fourth_letter_of_fourth_word(text):
  return text.split()[3][3]
​
function_list = [number_of_words, second_word, fourth_letter_of_fourth_word]
​
my_text = 'Mary had a little lamb'
map_obj = map(lambda f: f(my_text), function_list)
​
feature_list = list(map_obj)
​
print(feature_list)
[5, 'had', 't']

Conclusion


In this guide, we've explored the functionality of lambda functions in Python. We've seen that lambda functions are anonymous functions to be used as an inline function parameter for other functions. We've seen some use cases as well as when not to use them.

When programming, it is important to keep in mind Donald Knuth's quote: "Programs are meant to be read by humans and only incidentally for computers to execute." With this in mind, lambda functions are a useful tool to simplify our code, but should be used wisely.

Last Updated: May 16th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms