Monday, August 25, 2025

🐍LAMDA FUNCTION

Sometimes, you need a quick, one-line function without the hassle of using def. That’s where lambda functions come in.

1) What is a Lambda Function?

A lambda function is a small, anonymous function defined using the keyword lambda. Unlike normal functions created with def, lambda functions:

  • Can have any number of arguments but only one expression.
  • Do not need a name (anonymous).
  • Return the value of the expression automatically (no return keyword needed).

# Syntax
lambda arguments: expression

# Example
square = lambda x: x * x
print(square(5))  # Output: 25

2) Basic Examples


# Add two numbers
add = lambda a, b: a + b
print(add(3, 4))  # Output: 7

# Check even or odd
is_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(is_even(5))  # Output: Odd

3) Why Use Lambda Functions?

  • Quick throwaway functions you don’t want to define with def.
  • Used with higher-order functions like map(), filter(), sorted(), and reduce().
  • Helps keep code shorter and cleaner for simple operations.

4) Using Lambda with map(), filter(), and sorted()


# Double each number using map()
nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
print(doubled)  # [2, 4, 6, 8, 10]

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

# Sort by second element in tuple
pairs = [(1, 2), (3, 1), (5, 0)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)  # [(5, 0), (3, 1), (1, 2)]

5) Common Mistakes

  • Trying to write multiple statements: Lambda can only have one expression, not multiple lines.
  • Using for complex logic: If it gets too long, use def instead.
  • Forgetting it returns automatically: No need to use return.

# ❌ Invalid: multiple statements
lambda x: (y = x + 1; y * 2)  # SyntaxError

💡 Try It Yourself

  1. Write a lambda function to find the cube of a number.
  2. Use map() with lambda to convert a list of strings to uppercase.
  3. Use filter() with lambda to get numbers divisible by 3 from a list.

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??