Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Functions
  5. Lambda Function

Lambda Function

A lambda function in Python is a small anonymous function defined using the lambda keyword.

  • It is used to create quick, single-expression functions without needing to formally define them using def.

Syntax:

lambda arguments: expression
  • lambda is the keyword.
  • arguments are input parameters (can be more than one).
  • expression is the operation or result (only one expression, no statements).

Advantages of Lambda Functions:

  • Useful for short, quick functions.
  • Helps reduce code clutter when passing functions as arguments.
  • Ideal for functional programming use cases.

Limitations of Lambda Functions:

  • Only one expression is allowed.
  • Cannot contain multiple statements or annotations.
  • Less readable for complex logic.
  • Here, square is a lambda function that takes one input x and returns x * x.
square = lambda x: x * x
print(square(4))  # Output: 16
  • This lambda takes two arguments and returns their sum.
add = lambda a, b: a + b
print(add(3, 5))  # Output: 8
  • A lambda that returns “Even” if the number is even, otherwise “Odd”:
check_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check_even(7))  # Output: Odd

Lambda functions are often used with functions like map(), filter(), and sorted().

  1. Using with map():
    • Applies a lambda to each item in a list.
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
print(squares)  # Output: [1, 4, 9, 16]
  1. Using with filter():
    • Filters items based on a condition.
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 = = 0, nums))
print(evens)  # Output: [2, 4, 6]
  1. Using with sorted():
    • Sort a list of tuples by the second element.
pairs = [(1, 3), (2, 1), (4, 2)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)  # Output: [(2, 1), (4, 2), (1, 3)]

How can we help?

Leave a Reply

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