Lambda Functions

Lambda Functions in Python: Sometimes you need a small function for a quick task, like sorting a list or doing a simple calculation once, and you don't want to…

Concept Explanation

Sometimes you need a small function for a quick task, like sorting a list or doing a simple calculation once, and you don't want to go through the whole process of using the def keyword to give it a formal name.

In Python, Lambda Functions (also known as Anonymous Functions) allow you to write a one-line function without a name. They are meant for "throwaway" logic—simple operations that are passed as arguments to other functions like map(), filter(), or sort().


Syntax or Core Structure

The Lambda Formula

lambda arguments : expression

  • Arguments: Any number of inputs (just like regular functions).
  • Expression: A single line of code that is executed and automatically returned.
# A regular function
def square(x):
    return x * x

# The same thing as a lambda
lambda_square = lambda x : x * x

print(lambda_square(5)) # 25

Code Example #1 (Basic)

Using lambda functions with multiple arguments.

# Lambda with two arguments
add = lambda a, b : a + b
print(f"Sum: {add(10, 20)}")

# Lambda with three arguments
multiply_three = lambda x, y, z : x * y * z
print(f"Product: {multiply_three(2, 3, 4)}")

Code Example #2 (Intermediate)

The true power of Lambdas comes when they are used inside higher-order functions like filter() and map().

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

# 1. Filter: Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")

# 2. Map: Square every number
squares = list(map(lambda x: x**2, numbers))
print(f"Squares: {squares}")

Real World Example

Imagine you are building a list of products for an e-commerce site, and you want to provide different ways to sort them (by price, by name, etc.).

# 🛍️ Product Catalog
products = [
    {"name": "Laptop", "price": 1200},
    {"name": "Mouse", "price": 25},
    {"name": "Keyboard", "price": 75}
]

# Sort by Price (Low to High)
products.sort(key=lambda p: p["price"])
print(f"Cheapest first: {products[0]['name']}")

# Sort Alphabetically by Name
products.sort(key=lambda p: p["name"])
print(f"First alphabetically: {products[0]['name']}")

Common Mistakes

  1. Adding Multiple Expressions: A lambda can only have ONE expression. You cannot have loops, multiple lines, or if/elif/else blocks (though you can use a ternary operator like x if condition else y).
  2. Overusing Lambdas: If your lambda starts looking like Morse code because it's so complex, just use def. Readability is more important than being concise.
  3. Hard to Debug: Because they don't have a name, traceback errors for lambdas just say <lambda>, which makes it harder to find which specific one caused the crash in a large file.

Best Practices

  • Keep it Simple: Only use lambdas for logic that fits comfortably on one short line.
  • Pair with Functional Tools: Lambdas are best used as the "engine" inside functions like sorted(), min(), max(), filter(), and map().

Practice Exercises

  1. The Multiplier: Create a lambda function that takes one argument and returns it multiplied by 10.
  2. Word Filter: Given a list of words, use filter() and a lambda to create a new list containing only words that have more than 5 characters.
  3. Price Tagger: Given a list of numbers (prices), use map() and a lambda to return a list of strings where each number has a "$" sign added to it (e.g., [10, 20] -> ["$10", "$20"]).