Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is lambda in Python

Understanding Lambda in Python

When you're starting out in the world of programming, you'll come across various concepts that might seem daunting at first. One such concept in Python is the "lambda" function. Let's break it down into simple terms and explore how it works with examples that will help you grasp the idea more intuitively.

The Basics of Lambda Functions

A lambda function in Python is like a small, one-time-use, anonymous function that you can create without needing to formally define it using the def keyword. Think of it as a shortcut to create simple functions on the fly. The term "anonymous" here means that the function doesn't have a name.

When to Use Lambda Functions

Imagine you're writing a letter and you need to seal it with a sticker. You wouldn't go out and buy a whole roll of stickers for just one letter, right? Similarly, if you need a simple function for a short period within your code, you can use a lambda function instead of defining a full function with a name.

Lambda functions are commonly used when you need a function for a short duration, and it's going to be used only once. They are perfect for simple operations that can be expressed in a single line of code.

The Syntax of Lambda Functions

The basic syntax of a lambda function is:

lambda arguments: expression

Here, lambda is a keyword that tells Python we're about to declare an anonymous function. The arguments are the inputs for your function, similar to the parameters you would put in a regular function. The expression is what you want your function to do with the arguments, and it's limited to just one line.

A Simple Example

Let's look at an example to make things clearer. Suppose you want to create a function that adds 10 to any number you give it. Using the traditional function definition, you would do something like this:

def add_ten(number):
    return number + 10

print(add_ten(5)) # This will output 15

Now, let's achieve the same result using a lambda function:

add_ten_lambda = lambda number: number + 10

print(add_ten_lambda(5)) # This will also output 15

In the lambda version, we didn't have to use def or return. The lambda function is more concise and is defined in just one line.

Working with Multiple Arguments

Lambda functions can take more than one argument. Let's say you want to multiply two numbers. Here's how you could do it with a lambda function:

multiply = lambda x, y: x * y

print(multiply(2, 3)) # Outputs 6

Using Lambda Functions with Python Built-in Functions

Lambda functions become extremely useful when you combine them with built-in Python functions like map(), filter(), and sorted().

Using map()

The map() function takes a function and an iterable (like a list) and applies that function to every item in the iterable. Here's how you can use a lambda function with map() to square every number in a list:

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

print(list(squared)) # Outputs [1, 4, 9, 16, 25]

Using filter()

The filter() function is used to filter out elements from a list. It takes a function and an iterable, and it creates a new list with elements for which the function returns True. Here's an example using a lambda function to filter out only even numbers from a list:

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

print(list(even_numbers)) # Outputs [2, 4]

Using sorted()

The sorted() function sorts an iterable. You can specify a lambda function for its key parameter to decide how the sorting should be done. For instance, if you have a list of tuples where each tuple contains a name and an age, you can sort the list by age like this:

people = [('Alice', 25), ('Bob', 30), ('Cathy', 20)]
sorted_people = sorted(people, key=lambda person: person[1])

print(sorted_people) # Outputs [('Cathy', 20), ('Alice', 25), ('Bob', 30)]

Intuition and Analogies

To further help you understand lambda functions, let's use an analogy. Imagine a lambda function as a tool in your toolbox that you use once and then throw away. It's not something you keep and cherish for future use. It's there for convenience and to make the task at hand easier without adding extra clutter to your toolbox.

Limitations of Lambda Functions

While lambda functions are useful, they have their limitations. They can only contain expressions and can't have statements. This means you can't use loops or print within a lambda function. They are meant to be simple and are not suitable for complex operations.

Conclusion

Lambda functions in Python are like the Swiss Army knife of programming tools – small, handy, and perfect for a quick fix. They allow you to write cleaner and more efficient code when used correctly. As a beginner, you might not use them right away, but as you grow more comfortable with Python, you'll find them to be a powerful feature that can save you time and effort. So next time you come across a situation that requires a simple, one-off function, remember the lambda – your compact and anonymous helper in the vast world of Python programming.