Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is a lambda function in Python

Understanding Lambda Functions in Python

When you're just starting out in programming, you might feel overwhelmed by the various concepts and terms that are thrown your way. One such term you'll encounter in Python is the "lambda function". But don't worry, we'll break it down together, and by the end of this post, you'll not only understand what a lambda function is, but also how to use it effectively in your own code.

The Basics of Lambda Functions

In the simplest of terms, a lambda function is a small anonymous function — a function without a name. It can take any number of arguments, but can only have one expression. Think of it like a shortcut or a mini-function that you write in just one line of code.

To give you an initial intuition, imagine you're writing a short note instead of a full letter. The note (lambda function) is quick and to the point, while the letter (regular function) is longer and more detailed.

Let's start with a regular Python function:

def add(a, b):
    return a + b

result = add(3, 4)
print(result)  # Output: 7

This function add takes two arguments, a and b, adds them together, and returns the result. Now, let's rewrite this as a lambda function:

add = lambda a, b: a + b

result = add(3, 4)
print(result)  # Output: 7

Notice how we've condensed the entire function into a single line of code. The keyword lambda is followed by the arguments (a and b), a colon, and then the expression (a + b) that gets evaluated and returned.

Why Use Lambda Functions?

So, why would we use lambda functions if we can write regular functions? Lambda functions are useful when you need a simple function for a short period of time and you are interested in quick, throwaway functionality that is not going to be reused elsewhere.

An analogy might be using a disposable plate instead of a regular one when you're having a quick snack. It's convenient and serves the purpose without the need for something more durable.

Lambda Functions in Action

One common use case for lambda functions is when working with lists or collections. Python has built-in functions like map(), filter(), and sorted() that work well with lambda functions.

Using map() with Lambda

The map() function applies a given function to each item of an iterable (like a list) and returns a list of the results.

Here's an example without lambda:

def square(number):
    return number ** 2

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(square, numbers))

print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

Now, let's use a lambda function:

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))

print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

Using filter() with Lambda

The filter() function creates a list of elements for which a function returns true.

Here's an example without lambda:

def is_even(number):
    return number % 2 == 0

numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(is_even, numbers))

print(even_numbers)  # Output: [2, 4]

And with a lambda function:

numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers)  # Output: [2, 4]

Using sorted() with Lambda

The sorted() function sorts a list. You can use a lambda function to specify a custom sort order.

fruits = ['strawberry', 'fig', 'apple', 'cherry', 'banana']
sorted_fruits = sorted(fruits, key=lambda fruit: len(fruit))

print(sorted_fruits)  # Output: ['fig', 'apple', 'banana', 'cherry', 'strawberry']

Here, the lambda function helps to sort the fruits by their length.

When Not to Use Lambda Functions

Lambda functions are great for simple operations, but they have their limitations. If your function is complex and requires multiple expressions or statements, it's better to define a regular function. This is because lambda functions are designed to be simple and concise; anything that complicates that should likely be a regular function for the sake of clarity and maintainability.

Conclusion

Lambda functions in Python are like the Swiss Army knife of programming tools: small, convenient, and perfect for a specific task. They allow you to write quick, disposable functions on the fly, which can make your code more readable and efficient when used appropriately. However, like the tools on a Swiss Army knife, they are not always the best choice for every task. When you need something more substantial, it's better to write a full function.

As you continue your programming journey, you'll find the right balance between using lambda functions and regular functions. Remember, the goal is to write code that not only works but is also easy to understand and maintain. Keep practicing, and soon you'll wield lambda functions with the finesse of a seasoned Pythonista!