Python

How to Use Lambda Functions for Cleaner Python Code

One-line anonymous functions in Python can be defined quickly using lambda functions. They can be used to improve the readability and efficiency of the code, particularly when working with data. They are accommodating when we only need a basic function temporarily and don’t want to use the “def” keyword to define a complete function. Lambda functions can simplify the code by eliminating unnecessary function definitions that clutter it up.

Syntax:

The lambda function’s basic syntax is as follows:

lambda arguments: expression

  • arguments: The input parameters for the lambda function.
  • expression: A single expression evaluated by the lambda function and then returned.

Assigning Lambda Functions to Variables

For straightforward tasks without a separate named function, use the lambda functions. For instance, the square of an integer can be calculated using the lambda function as follows:

The first line of code defines a lambda function called “lambda_square”. This function/method accepts one argument, “x”, and returns the value of the square after calculating.

The second line of code assigns the result of calling the “lambda_square” function with the argument of 5 to the “square_result” variable.

The value of the “square_result” variable is printed on the third line of code.

lamda_square=lambda x: x ** 2

square_result = lamda_square(5)

print(square_result)

Here is the output of the code:

This is similar to the next named function:

def square(x):

return x ** 2

Using Lambda Functions with Built-In Functions

To make the code more concise, lambda functions are frequently employed with already developed (built-in) methods like map(), filter(), and sorted(). The following code finds the cube of each number in a list by combining the “map” function with the lambda function (built-in function):

input_numbers_arr = [1, 2, 3, 4, 5]

# Cube each number in the list using a lambda function

cube_calculated_arr = list (map (lambda y: y**3, input_numbers_arr))

print(cube_calculated_arr)

The previously shown code produced the following output:

Filter Function

Filtering the data can be done more quickly and efficiently by combining the lambda functions with the filter() function. The Python code uses a lambda function to filter a list of numbers. Numbers_list is a list of numbers that are specified in the first line of code.

The numbers_list list is filtered using the filter() method in the second line of code only to contain the even numbers. When a function and an iterable are passed as arguments, the filter() method returns a list of the iterable elements for which the function returns “True”. In the given example, the lambda function receives a single parameter, “y” (or any letter). It returns “True” if the value of “y” is completely divisible by 2. Otherwise, it is even and false.

The “filter” method is used in the following line of code to filter the numbers_list list so that only the odd numbers are displayed. In this example, “y” is the only parameter that the lambda function accepts.

Print the even number and odd numbers as well, respectively, at the end of the code.

The whole code is shown as follows:

LamdaFilter.py:

input_Integers_Array = [1, 2, 4, 3, 6, 5, 8, 7, 10, 9]
evb_nums_arr = list(filter(lambda y: y % 2 == 0, input_Integers_Array))
odd_nums_arr = list(filter(lambda y: y % 2 == 1, input_Integers_Array))
print(evb_nums_arr)
print(odd_nums_arr)

Here is the output of the code:

Sort Using the Lambda Expression

Using the Python lambda functions, the code arranges a list of movie titles alphabetically and by length. The first line of code defines a list of movie titles called “movies_names_list”.

The movies_names_list list is sorted by movie name length using the sorted() method in the fifth line of code. The sorted() method’s key parameter designates the function to compare the list’s items. The important function in this scenario is a lambda function that accepts “x” as an input and returns x’s length. The following code outputs the movie names in sorted order:

The movies_names_list list is alphabetically sorted using the sorted() method in the fourth line of code. In this instance, the lambda function only accepts the “x” parameter and returns “x” in lowercase. The sorted list of movie names is printed in the following line of code:

LamdaSort.py:

#movies List
movies_names_list = ["The God Father", "Saving Private Ryan", "Back to the Future", "Mission Impossible", "Gladiator"]
# Sort the list by movie name length
sorted_movies_names = sorted(movies_names_list, key=lambda x: len(x))
#print the sorted movies list
print(sorted_movies_names)
# Sort the list by movie name (alphabetically) using a lambda function
sorted_movies_names = sorted(movies_names_list, key=lambda x: x.lower())
print(sorted_movies_names)

When the code is executed, it prints the following output:

Lambda Functions in Key Functions

The following code example specifies the custom sorting or finding the criteria using a lambda expression as the key argument in functions like sorted, max, and min. The “person” list, which includes the names and ages of the people, is defined in the code start. The following lines of code use the max and min functions to obtain the maximum and minimum ages using the lambda expressions. The list of people is sorted by age in the following lines of code and the sorted list is printed:

Python Code LamdaFunc.py:

#people List
people_list = [('Alice', 25), ('Bob', 30), ('Carol', 22), ('Dave', 28)]
# Get the maximum and minimum age using lambda functions
max_age = max(people_list, key=lambda x: x[1])[1]
min_age = min(people_list, key=lambda x: x[1])[1]
print("Maximum age:", max_age)
print("Minimum age:", min_age)
sorted_people_list_by_age=sorted(people_list,key=lambda x: x[1])
print(sorted_people_list_by_age)

Here is the output:

Avoid a Complex Logic

Consider a scenario where we have a list of student records and we want to remove any that fall below a certain minimum average score. As the logic becomes more intricate, it is advisable to switch to a regular “def” function rather than starting with a lambda function to accomplish this.

Using a student dictionary as its input, the lambda function outputs that if the student’s average score is higher than or equal to 85, the statement is false. Otherwise, it is false. Now, we utilize a lambda function (worse for complex logic):

ComplexLambda.py:

students_list = [
    {"name": "Alice", "scores": [85, 90, 78]},
    {"name": "Bob", "scores": [92, 88, 95]},
    {"name": "Charlie", "scores": [78, 85, 80]},
]
# Using a lambda function with complex logic
filtered_students_list = filter(lambda std: sum(std["scores"]) / len(std["scores"]) >= 85, students_list)
for std in filtered_students_list:
    print(f"{std['name']} passed with an average score.")

Here is the output:

A black background with white text Description automatically generated

Using a regular “def” function improves the readability for complex logic. The code defines two functions: calculate_averagescore() and has_passed(). The calculate_averagescore() function takes a list of scores as input and returns the average score. The has_passed() function takes a student dictionary as input and returns “True” if the student’s average score is greater than or equal to 85 and returns “False” otherwise. It is very easy to understand and is very simple compared to the previously written code. The output of both codes are the same. The lambda expression code is written in a single line.

SimpleFunc.py:

def calculate_averagescore(inputscores):
    return sum(inputscores) / len(inputscores)
def has_passed(student):
    student_average_score = calculate_averagescore(student["scores"])
    return student_average_score >= 85
students = [
    {"name": "Alice", "scores": [85, 90, 78]},
    {"name": "Bob", "scores": [92, 88, 95]},
    {"name": "Charlie", "scores": [78, 85, 80]},
]
# Using a regular def function for better readability
filtered_students = filter(has_passed, students)
for student in filtered_students:
    print(f"{student['name']} passed with an average score.")

To run the code, simply open the command prompt, navigate to the working directory, and enter the Python command to execute the code. Here is the working output of the code:

Concussion

In conclusion, lambda functions are an effective Python tool for writing quick, standalone functions. When used properly, especially in conjunction with built-in functions and for simple operations, they can make the code cleaner and easier to comprehend. However, it’s crucial to maintain a balance and refrain from overusing them because normal functions that are written with “def” are better suited for sophisticated logic.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content