Lambda Functions in Python: The Ultimate Guide to Simplifying Your Code

Mutakilu Mukailu
4 min readMar 29, 2023

--

Lambda functions, also known as anonymous functions, are a feature in Python that allow us to create small, single-line functions without a name. These functions are useful in situations where we need to pass a function as an argument to another function, or when we want to define a function quickly without defining it explicitly. In this article, we will explore the basics of lambda functions and how they can be used in Python.

To understand what lambda functions are, let’s first take a look at a regular Python function:

def add_numbers(x, y):
return x + y

This function takes two arguments, x and y, and returns their sum. We can call this function like this:

result = add_numbers(3, 5)
print(result)

This will output 8.

Now let’s see how we can create the same function using a lambda function:

add_numbers = lambda x, y: x + y

This lambda function takes two arguments, x and y, and returns their sum. We can call this function in the same way as the regular function:

result = add_numbers(3, 5)
print(result)

This will also output 8.

As you can see, the lambda function has the same functionality as the regular function, but it is defined in a different way. The lambda function starts with the keyword lambda, followed by the argument(s) and a colon, and then the expression that the function should return. The result of the expression is automatically returned by the lambda function.

Lambda functions can be used in many ways in Python. One of the most common use cases is when we want to sort a list of objects based on a specific attribute. For example, let’s say we have a list of dictionaries, where each dictionary represents a person with their name and age:

people = [    {"name": "Alice", "age": 25},    {"name": "Bob", "age": 18},    {"name": "Charlie", "age": 32}]

We can sort this list based on the age of the people using the sorted() function and a lambda function:

sorted_people = sorted(people, key=lambda x: x["age"])

The sorted() function takes two arguments: the list to be sorted and a key function that returns the value to be used for sorting. In this case, we are using a lambda function that returns the value of the "age" key of each dictionary. The result of this operation is a new list with the same objects, but sorted by age:

[{"name": "Bob", "age": 18}, {"name": "Alice", "age": 25}, {"name": "Charlie", "age": 32}]

Another use case for lambda functions is when we want to create a new function dynamically, based on some input. For example, let’s say we want to create a function that takes a list of numbers and returns a new list with only the even numbers. We can define this function using a lambda function like this:

def create_filter_function(condition):
return lambda x: x % 2 == 0 if condition == "even" else x % 2 != 0

filter_function = create_filter_function("even")
result = list(filter(filter_function, [1, 2, 3, 4, 5, 6]))
print(result)

The create_filter_function() function returns a lambda function that takes a single argument x and returns True if x is even (if condition is "even") or False if condition is "odd"). We then use the filter() function with this lambda function to filter out the even numbers from the input list. The result of this operation is a new list containing only the even numbers [2, 4, 6].

Lambda functions can also be used in combination with other Python features, such as list comprehension. For example, let’s say we want to create a new list that contains the squares of the numbers in another list. We can use a lambda function with a list comprehension to achieve this:

numbers = [1, 2, 3, 4, 5]
squares = [(lambda x: x**2)(n) for n in numbers]
print(squares)

In this example, we define a lambda function that takes a single argument x and returns its square. We then use this lambda function in a list comprehension to create a new list containing the squares of the numbers in numbers.

Lambda functions are a powerful and versatile feature in Python, allowing us to create small, single-line functions quickly and easily. They can be used in many different contexts, from sorting lists to creating new functions dynamically. By understanding the basics of lambda functions, you can take advantage of this powerful tool in your own Python code.

By understanding how to use lambda functions, you can improve the readability and efficiency of your Python code, making it easier to understand and maintain.

I hope this article has given you a solid understanding of lambda functions in Python and how you can use them to simplify your code. By following the examples and applications described here, you can start using lambda functions in your own Python code today.

If you found this article helpful, please consider sharing it with your friends and colleagues who are also interested in programming. By liking and sharing this article, you can help spread the word about the power of lambda functions in Python and help others improve their coding skills.

For more Python tips and tutorials, be sure to follow this Medium account and stay tuned for more informative and engaging articles. Thank you for reading!

--

--

Mutakilu Mukailu

Experienced data scientist skilled in extracting insights from complex data sets. Passionate about using data to solve real-world problems.