Lambda Functions in Python

Lambda Functions in Python

Lambda functions are small, anonymous functions defined using the lambda keyword. They can take any number of arguments but can only have one expression.

Basic Syntax

python

lambda arguments: expression

Simple Examples

1. Basic Lambda Function

python

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

# Equivalent lambda function
add_lambda = lambda x, y: x + y

print(add(5, 3))        # Output: 8
print(add_lambda(5, 3)) # Output: 8

2. Single Argument Lambda

python

# Double a number
double = lambda x: x * 2
print(double(7))  # Output: 14

# Square a number
square = lambda x: x ** 2
print(square(4))  # Output: 16

Lambda with Built-in Functions

3. Using with map()

python

numbers = [1, 2, 3, 4, 5]

# Double each number using map + lambda
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)  # Output: [2, 4, 6, 8, 10]

4. Using with filter()

python

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Filter even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # Output: [2, 4, 6, 8, 10]

# Filter numbers greater than 5
greater_than_5 = list(filter(lambda x: x > 5, numbers))
print(greater_than_5)  # Output: [6, 7, 8, 9, 10]

5. Using with sorted()

python

# Sort by length of words
words = ["apple", "banana", "cherry", "date"]
sorted_by_length = sorted(words, key=lambda x: len(x))
print(sorted_by_length)  # Output: ['date', 'apple', 'banana', 'cherry']

# Sort by last character
sorted_by_last_char = sorted(words, key=lambda x: x[-1])
print(sorted_by_last_char)  # Output: ['banana', 'apple', 'date', 'cherry']

Practical Examples

6. Simple Calculator Operations

python

operations = {
    'add': lambda x, y: x + y,
    'subtract': lambda x, y: x - y,
    'multiply': lambda x, y: x * y,
    'divide': lambda x, y: x / y if y != 0 else "Cannot divide by zero"
}

print(operations['add'](10, 5))       # Output: 15
print(operations['multiply'](4, 6))   # Output: 24
print(operations['divide'](10, 2))    # Output: 5.0

7. Conditional Logic in Lambda

python

# Check if number is positive
is_positive = lambda x: True if x > 0 else False
print(is_positive(5))   # Output: True
print(is_positive(-3))  # Output: False

# Grade classifier
grade = lambda score: "Pass" if score >= 50 else "Fail"
print(grade(75))  # Output: Pass
print(grade(45))  # Output: Fail

8. Multiple Arguments

python

# Calculate area of rectangle
area = lambda length, width: length * width
print(area(5, 10))  # Output: 50

# String formatting
greet = lambda name, age: f"Hello {name}, you are {age} years old!"
print(greet("Alice", 25))  # Output: Hello Alice, you are 25 years old!

Advanced Examples

9. Immediately Invoked Lambda

python

# Lambda function called immediately
result = (lambda x, y: x ** y)(2, 3)
print(result)  # Output: 8

# Another example
message = (lambda name: f"Welcome, {name}!")("Bob")
print(message)  # Output: Welcome, Bob!

10. Lambda in List Comprehensions

python

# Create a list of functions
functions = [lambda x, n=i: x + n for i in range(5)]
for i, func in enumerate(functions):
    print(f"func({10}, n={i}) = {func(10)}")

11. Using with reduce()

python

from functools import reduce

numbers = [1, 2, 3, 4, 5]

# Calculate product using reduce + lambda
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 120 (1*2*3*4*5)

# Find maximum number
max_num = reduce(lambda x, y: x if x > y else y, numbers)
print(max_num)  # Output: 5

When to Use Lambda Functions

Good for:

  • Simple, one-line operations
  • Functions used only once
  • As arguments to higher-order functions (mapfiltersorted, etc.)

Not good for:

  • Complex logic (use regular def functions)
  • Functions that need documentation strings
  • Functions with multiple statements

Key Points to Remember

  1. Anonymous: Lambda functions don’t have names (unless assigned to a variable)
  2. Single Expression: Can only contain one expression
  3. No Statements: Cannot include statements like returnpassassert, etc.
  4. Implicit Return: The expression is automatically returned

Lambda functions make your code more concise and readable when used appropriately for simple operations!

Similar Posts

  • Python Statistics Module

    Python Statistics Module: Complete Methods Guide with Examples Here’s a detailed explanation of each method in the Python statistics module with 3 practical examples for each: 1. Measures of Central Tendency mean() – Arithmetic Average python import statistics as stats # Example 1: Basic mean calculation data1 = [1, 2, 3, 4, 5] result1 = stats.mean(data1) print(f”Mean of…

  • List of machine learning libraries in python

    Foundational Libraries: General Machine Learning Libraries: Deep Learning Libraries: Other Important Libraries: This is not an exhaustive list, but it covers many of the most important and widely used machine learning libraries in Python. The choice of which library to use often depends on the specific task at hand, the size and type of data,…

  • re Programs

    The regular expression r’;\s*(.*?);’ is used to find and extract text that is located between two semicolons. In summary, this expression finds a semicolon, then non-greedily captures all characters up to the next semicolon. This is an effective way to extract the middle value from a semicolon-separated string. Title 1 to 25 chars The regular…

  • Examples of Python Exceptions

    Comprehensive Examples of Python Exceptions Here are examples of common Python exceptions with simple programs: 1. SyntaxError 2. IndentationError 3. NameError 4. TypeError 5. ValueError 6. IndexError 7. KeyError 8. ZeroDivisionError 9. FileNotFoundError 10. PermissionError 11. ImportError 12. AttributeError 13. RuntimeError 14. RecursionError 15. KeyboardInterrupt 16. MemoryError 17. OverflowError 18. StopIteration 19. AssertionError 20. UnboundLocalError…

  • What is Quantum Computing? A Beginner’s Guide to the Future of Technology

    What is Quantum Computing? Quantum computing is a revolutionary approach to computation that leverages the principles of quantum mechanics to perform complex calculations far more efficiently than classical computers. Unlike classical computers, which use bits (0s and 1s) as the smallest unit of information, quantum computers use quantum bits (qubits), which can exist in multiple…

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”—the regex engine looks ahead in the string to see if the pattern inside…

Leave a Reply

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