Introduction to Lambda Functions

A lambda function is a small, anonymous function that can take any number of arguments but can only have one expression.

Syntax:

lambda arguments: expression

Example:

# Regular function

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

add = lambda x, y: x + y
print(add(2, 3)) # Output: 5

In the above example, we have created a lambda function named ‘add’ which takes two arguments ‘x’ and ‘y’ and returns their sum.

Lambda functions are often used as arguments to higher-order functions, such as map(), filter(), and reduce().

Example:

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

In the above example, we have used the map() function to apply the lambda function (x**2) to each element in the ‘nums’ list.

Lambda functions are also useful in sorting and filtering data.

Example:

students = [('Alice', 23), ('Bob', 19), ('Charlie', 21), ('David', 18)]
students.sort(key=lambda x: x[1])
print(students) # Output: [('David', 18), ('Bob', 19), ('Charlie', 21), ('Alice', 23)]

In the above example, we have used the sort() method to sort the ‘students’ list based on their age, which is the second element of each tuple.

Lambda functions are a powerful feature of Python, but they should be used judiciously. They are not always the best solution for every problem, and sometimes a named function is more readable and easier to understand.

That’s it! You now know how to use lambda functions in Python.


Recap

  1. A lambda function is a small, anonymous function in Python.
  2. Lambda functions are defined using the keyword lambda, followed by one or more arguments, a colon, and the function body.
  3. Lambda functions can take any number of arguments, but can only have one expression in the function body.
  4. Lambda functions can be used anywhere a function is required, such as in the map, filter, and reduce functions.
  5. Lambda functions can be used to write more concise and readable code, especially when the function is only needed once.
  6. Lambda functions can be assigned to variables, passed as arguments to other functions, or used directly in expressions.
  7. Lambda functions can be used in combination with other built-in functions and data structures in Python, such as lists and dictionaries.
  8. Lambda functions can help reduce code duplication and improve code modularity in Python programs.

Hello, I’m Anuj. I make and teach software.

My website is free of advertisements, affiliate links, tracking or analytics, sponsored posts, and paywalls.
Follow me on LinkedIn, X (twitter) to get timely updates when I post new articles.
My students are the reason this website exists. ❤️

Feedback Display