How do lambda functions work in Python?

sakshisukla

Member
Lambda functions in Python are anonymous, single-expression functions defined using the lambda keyword. Unlike regular functions created with def, lambda functions do not have a name and are typically used for short, simple operations. The basic syntax is:


lambda arguments: expression


For example, a lambda function that adds two numbers looks like this:

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


Key Features of Lambda Functions:


  1. Single Expression – Lambda functions can only contain one expression, which is evaluated and returned.
  2. No Explicit Return – The result is automatically returned without using the return keyword.
  3. Used for Short Tasks – They are mostly used when a small function is required for immediate use.
  4. Can Be Used with Higher-Order Functions – Lambda functions are commonly used with functions like map(), filter(), and reduce().

Examples of Lambda Functions in Action


  1. Using map() to square a list of numbers:
    python
    CopyEdit
    numbers = [1, 2, 3, 4]
    squared = list(map(lambda x: x**2, numbers))
    print(squared) # Output: [1, 4, 9, 16]
  2. Using filter() to get even numbers from a list:
    python
    CopyEdit
    evens = list(filter(lambda x: x % 2 == 0, numbers))
    print(evens) # Output: [2, 4]
  3. Sorting a list of tuples based on the second element:
    python
    CopyEdit
    pairs = [(1, 3), (2, 2), (4, 1)]
    sorted_pairs = sorted(pairs, key=lambda x: x[1])
    print(sorted_pairs) # Output: [(4, 1), (2, 2), (1, 3)]

Mastering lambda functions is essential for writing concise, efficient code in Python. If you want to deepen your Python expertise, consider enrolling in a Python certification course to enhance your skills.
 
Back
Top