Lambda Functions in Python

Introduction

In this article, we are going to be discussing lambda functions in python. We are going to explore ways which we can use lambda functions to write shorter codes. If you are familiar with Javascript then lambda functions should not seem too strange except for some key differences. The python lambda function can only have one expression in its body as opposed to Javascript anonymous functions.

Usage and Examples

The best way to explain lambda functions is via examples. Let's say we have a function that returns the square of the number sent via the function's argument.

def square(number):
    return number * number

twoSquared = square(2)
print(twoSquared) # 4

The above code snippet can be rewritten using a lambda function as:

square = lambda number: number * number

twoSquared = square(2)
print(twoSquared) # 4

Note that you do not need to include a return statement in your lambda function. The expression is implicitly returned. You can also pass lambda functions as arguments to a function. For example, let's create a map function that has the following specifications:

  • Accepts a list and a function as arguments
  • Executes the function with each element in the list and saves the returned value in another list.
  • Returns the list containing the returned value as the function's result.
def square(number):
    return number * number

def map(num_list, func):
    ret_list = []
    for num in num_list:
        ret = func(num)
        ret_list.append(ret)
    return ret_list

numbers = [1,2,3,4]
numbersSquared = map(numbers, square)
print(numbersSquared) # [1, 4, 9, 16]

We can make the above code snippet shorter by making use of lambda functions. You can pass the func argument to the map function without having to declare it first as seen below:

def map(num_list, func):
    ret_list = []
    for num in num_list:
        ret = func(num)
        ret_list.append(ret)
    return ret_list

numbers = [1,2,3,4]
numbersSquared = map(numbers, lambda number: number * number)
print(numbersSquared) # [1, 4, 9, 16]

As you can see from the above code snippet, we achieved the same result with lambda functions while having to write lesser code.

Let us look at another example. Let us write a program that takes a list of student records and orders them based on certain criteria. A student record contains the student's name, age and score. We are going to make use of the python inbuilt sorted function to achieve this.

records = [{"name": "Favour", "age": 20, "score": 90}, {"name": "Moses", "age": 16, "score": 75}, {"name": "Dias", "age": 23, "score": 99}]

score_sorted_records = sorted(records, key=lambda record: record["score"])
print(score_sorted_records) # [{'name': 'Moses', 'age': 16, 'score': 75}, {'name': 'Favour', 'age': 20, 'score': 90}, {'name': 'Dias', 'age': 23, 'score': 99}]

age_sorted_records = sorted(records, key=lambda record: record["age"])
print(age_sorted_records) # [{'name': 'Moses', 'age': 16, 'score': 75}, {'name': 'Favour', 'age': 20, 'score': 90}, {'name': 'Dias', 'age': 23, 'score': 99}]

From the above code snippet, we use a lambda function to tell the sorted function the key we want to use to sort the student records. The lambda function is passed to the sorted function via the key keyword argument.

Summary

Python lambda functions are a way to write small anonymous functions. They can be applied to many use cases. They can accept any number of arguments, but they can only have one expression. They can be assigned to variables or passed directly as function arguments. They are commonly used when working with functions that accept functions as arguments.

I hope this article has been helpful in introducing to you how python lambda functions work and how to use them.

No Comments Yet