Lambda Functions#

Lambda functions are a powerful yet simple feature in many programming languages that can help you write concise and elegant code. This tutorial is designed for humanists with little to no programming experience, and we will use examples from literature to demonstrate the usefulness of lambda functions.

What are Lambda Functions?#

Lambda functions are small, anonymous functions that can be created and used on-the-fly without needing a formal function definition. In simpler terms, they are one-liner functions that don’t need a name. Why are lambda functions useful?

  • They allow for more concise and readable code.

  • They can be used as arguments to higher-order functions (functions that take other functions as inputs).

  • They are excellent for simple operations that don’t require a full function definition.

Basic syntax#

In Python, the syntax for creating a lambda function is:

lambda arguments: expression

The lambda keyword is followed by a list of arguments, a colon, and a single expression that the function will return.

For example, let’s say we have a simple function that combines a first name and a last name with a space:

def add_name(x, y):
    return x + " " + y
first_name = "William"
last_name = "Mattingly"
full_name = add_name(first_name, last_name)
print(full_name)
William Mattingly

We can rewrite this function as a lambda function like this:

add_name2 = lambda x, y: x + " " + y

Although this is not the intended use of the lambda function, we can call it now in the same way we did above with a regular function.

full_name2 = add_name2(first_name, last_name)
print(full_name2)
William Mattingly

Using lambda functions with our example lines#

The more common way to use lambda is to pass the lambda function to another function. You will often hear the term higher-order function in this scenario. A higher-order function is a function that can take one function as an input and return either a new function or some other value. When we use lambda in real scenarios, we often pass this anonymous function to a higher-order function in order to simplify our code. Let’s consider a few examples with the lines from “The Raven” by Edgar Alan Poe.

lines = [
    "Once upon a midnight dreary, while I pondered, weak and weary,",
    "Over many a quaint and curious volume of forgotten lore—",
    "While I nodded, nearly napping, suddenly there came a tapping,",
    "As of some one gently rapping, rapping at my chamber door.",
]

Example 1: Counting words in each line#

Let’s use a lambda function to count the number of words in each line. We can achieve this using the map() function, which applies a given function to each item in an iterable (like a list).

The map function is a higher-order function. In the previous tutorial, we saw that takes a function and an iterable as input, and returns a new iterable that contains the result of applying the function to each element of the original iterable.

Here’s an implementation of the map function in Python:

def map(func, iterable):
    result = []
    for item in iterable:
        result.append(func(item))
    return result

We can pass our anonymous lambda function to this map function. In this case, our lambda function will split each line and then count the length of each line. As a regular function, this would look like this:

def count_words(lines):
    def count_words_in_line(line):
        return len(line.split())
    word_count = []
    for line in lines:
        word_count.append(count_words_in_line(line))
    return word_count

In this code, the count_words function takes a list of strings lines as input and returns a list of integers representing the number of words in each line. The count_words_in_line function takes a single line as input and returns the number of words in that line. The count_words function uses a for loop to apply the count_words_in_line function to each line in lines and append the result to the word_count list.

This complex function can be reduced to a single line by leveraging map and lambda functions.

word_count = map(lambda line: len(line.split()), lines)

# Convert the result to a list and print it
print(list(word_count))
[11, 10, 10, 11]

Example 2: Sorting lines by length#

Another common usage of lambda is to use with the sorted() function. We can use a lambda function in the example below to sort the lines based on their length. The sorted() function can take a key argument, which is a function that defines how to sort the items. In this case, our lambda function will be the function that we pass to the key argument.

In the example below, we use lambda to sort the lines by their length.

sorted_lines = sorted(lines, key=lambda line: len(line))

# Print the sorted lines
for line in sorted_lines:
    print(line)
Over many a quaint and curious volume of forgotten lore—
As of some one gently rapping, rapping at my chamber door.
Once upon a midnight dreary, while I pondered, weak and weary,
While I nodded, nearly napping, suddenly there came a tapping,

Here, lambda line: len(line) is a lambda function that takes a single argument line and returns its length.

While not essential in code, lambda functions can reduce the need to have functions for functional code that may only have a single use in your code. Lambda functions are a powerful tool for writing concise and elegant code. They can be especially useful for humanists working with text data, as they allow for quick and simple manipulation of strings and lists.

Live Coding#

lines = [
    "Once upon a midnight dreary, while I pondered, weak and weary,",
    "Over many a quaint and curious volume of forgotten lore—",
    "While I nodded, nearly napping, suddenly there came a tapping,",
    "As of some one gently rapping, rapping at my chamber door.",
]