Working with Anonymous Function(Lambda) in Python

Introduction

In this article, we will discuss lambda functions in Python. A lambda function in Python is an anonymous function (a function without a name) that can have any number of arguments but only one expression. It is defined using the lambda keyword.

Syntax

lambda arguments: expression
  • lambda defines the function.
  • arguments are the input values.
  • expression is evaluated and returned.

Example 1. Basic Lambda Function

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

In the above example, add is a lambda function that takes two arguments and returns their sum.

Where to Use Lambda Functions?

Lambda functions are widely used with built-in functions like map(), filter(), and sorted(). Below are some examples.

1. Using Lambda with map()

The map() function applies a function to all items in an iterable.

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

2. Using Lambda with filter()

The filter() function selects elements based on a condition.

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

3. Using Lambda with sorted()

Lambda functions can be used as the key function in sorting.

students = [('Ankit', 25), ('Boby', 20), ('Chandan', 23)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)  # Output: [('Boby', 20), ('Chandan', 23), ('Ankit', 25)]

4. Using Lambda in List Comprehension

Lambda functions can be combined with list comprehensions.

numbers = [1, 2, 3, 4, 5]
square_numbers = [(lambda x: x**2)(x) for x in numbers]
print(square_numbers)  # Output: [1, 4, 9, 16, 25]

Lambda Function in Python

When to Use Lambda Functions?

  • When you need a small function for a short period.
  • When you don't want to define a full function using def.
  • When working with higher-order functions like map(), filter(), and sorted().

When Not to Use Lambda Functions?

  •  When the function is complex or needs multiple expressions.
  • When code readability is more important.
  • When debugging is required (lambda functions have no function name, making debugging harder).

Conclusion

Lambda functions in Python are a great tool for writing concise, readable, and efficient code. They are useful in situations where a small function is needed for a short period. However, for complex logic, using a traditional def function is recommended.

Up Next
    Ebook Download
    View all
    Learn
    View all