Lambda Functions

Loading

A lambda function in Python is a small, anonymous function defined using the lambda keyword. It can take multiple arguments but must have only one expression. Lambda functions are useful for short, simple operations where defining a full function is unnecessary.


1. Syntax of a Lambda Function

pythonCopyEditlambda arguments: expression
  • lambda: The keyword used to define a lambda function.
  • arguments: One or more inputs, similar to function parameters.
  • expression: A single expression evaluated and returned (no multiple statements allowed).

2. Basic Example of a Lambda Function

Example: Lambda Function to Add Two Numbers

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

Output:

8
  • Here, lambda x, y: x + y is equivalent to: pythonCopyEditdef add(x, y): return x + y

3. Lambda Function with One Argument

square = lambda x: x * x
print(square(4))

Output:

16

4. Using Lambda Functions with map()

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

Example: Squaring a List of Numbers

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

Output:

[1, 4, 9, 16, 25]

5. Using Lambda Functions with filter()

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

Example: Filtering Even Numbers

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

Output:

[2, 4, 6]

6. Using Lambda Functions with sorted()

The sorted() function can use a lambda function as a sorting key.

Example: Sorting a List of Tuples by Second Element

students = [("Alice", 25), ("Bob", 20), ("Charlie", 23)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)

Output:

[('Bob', 20), ('Charlie', 23), ('Alice', 25)]

7. Using Lambda Functions Inside Another Function

Example: Multiplication Function with Lambda

def multiplier(n):
return lambda x: x * n

double = multiplier(2)
print(double(5))

Output:

10
  • multiplier(2) returns lambda x: x * 2, making double(5) equal to 5 * 2 = 10.

8. Lambda Function with reduce()

The reduce() function (from functools) applies a function cumulatively.

Example: Summing a List of Numbers

from functools import reduce

numbers = [1, 2, 3, 4, 5]
sum_result = reduce(lambda x, y: x + y, numbers)
print(sum_result)

Output:

15

9. Comparison Between Lambda and Normal Functions

Regular Function

def cube(x):
return x ** 3

print(cube(3))

Lambda Equivalent

cube = lambda x: x ** 3
print(cube(3))

Both produce:

27

10. Limitations of Lambda Functions

  • Can only have one expression (no multiple statements).
  • Limited readability for complex logic.
  • Cannot contain return, loops, or assignments.

Leave a Reply

Your email address will not be published. Required fields are marked *