Lambda Functions in Python

Hello, fellow Python enthusiasts! Today, I’m excited to explain one of Python’s most important features: the lambda function. If you’ve been coding in Python for a while, you probably know a little about lambda functions. But what exactly are they, and how can they make your code more efficient and readable? Let me tell you here. In this tutorial, I will explain everything about Lambda functions in Python with examples.

What is a Lambda Function in Python?

A lambda function in Python is a small, anonymous function defined with the keyword lambda. Unlike regular functions that are defined using the def keyword, lambda functions are typically used for short, throwaway functions. They are especially useful when you need a simple function for a short period of time and don’t want to clutter your code with full function definitions.

Syntax of the Python Lambda Functions

The syntax of a lambda function in Python is below:

lambda arguments: expression
  • lambda: This keyword is used to declare a lambda function.
  • arguments: These are the inputs to the function, similar to parameters in a regular function.
  • expression: This is a single expression that is evaluated and returned.

Check out Python Function Naming Conventions

How to Use Python Lambda Functions

Now, let me show you how to use the Python lambda function with some examples.

Lambda functions are often used in scenarios where you need a simple function for a short period of time. They are commonly used with functions like map(), filter(), and sorted(), which expect a function as an argument.

Example 1: Basic Lambda Function

Here’s a basic example to explain the syntax and usage of a lambda function in Python:

# Regular function
def add(x, y):
    return x + y

# Lambda function
add_lambda = lambda x, y: x + y

# Using the lambda function
result = add_lambda(5, 3)
print(result)  # Output: 8

In this example, the lambda function add_lambda performs the same operation as the regular function add, but with much less code.

Here is the output you can see in the screenshot below:

lambda function in python

Example 2: Using Lambda with map()

The map() function applies a given function to all items in an input list. Here’s how you can use a lambda function with map() in Python:

numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)
print(list(squared))  # Output: [1, 4, 9, 16, 25]

In this example, the lambda function squares each number in the list.

Check out Python Functions vs Methods

Example 3: Using Lambda with filter()

The filter() function filters items out of a list based on a given condition. Lambda functions are perfect for this, here is an example for it.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))  # Output: [2, 4, 6, 8, 10]

Here, the lambda function filters out odd numbers, leaving only the even ones. You can see the exact output in the screenshot below:

lambda function in python example

Example 4: Using Lambda with sorted()

The sorted() function can also benefit from lambda functions, especially when you need to sort complex data structures. Let me show you an example.

states = [
    {'name': 'California', 'population': 39538223},
    {'name': 'Texas', 'population': 29145505},
    {'name': 'Florida', 'population': 21538187}
]

# Sort by population
sorted_states = sorted(states, key=lambda state: state['population'])
print(sorted_states)

In this example, we have a list of states with their respective populations. The lambda function sorts the list of dictionaries by the ‘population’ key, resulting in the states being ordered from the least to the most populous.

You can see the exact output in the screenshot below:

lambda function in python sort

Check out Lambda Functions in Python with If Condition

Advantages of Lambda Functions

  1. Concise Code: Lambda functions allow you to write concise and readable code.
  2. No Need for Function Names: Since they are anonymous, there’s no need to come up with unique function names.
  3. Functional Programming: Lambda functions are a key feature in functional programming, making it easier to pass functions as arguments.

When to Use Lambda Functions in Python

While lambda functions are powerful, they are not always the best choice. Here are some scenarios where using a lambda function is appropriate:

  • When you need a simple function for a short period.
  • When the function logic is straightforward and can be expressed in a single line.
  • When you want to pass a function as an argument to higher-order functions like map(), filter(), and sorted().

Conclusion

Lambda functions are a powerful feature in Python that can help you write more concise and readable code. They benefit small, throwaway functions and can be used effectively with higher-order functions. I hope this guide has given you a clear understanding of Python lambda functions and how to use them in your Python projects. Feel free to leave a comment below if you still have any questions.

You may also like:

Leave a Comment