Lambda Functions in Python
Lambda functions, also known as anonymous functions, are small, one-line functions that do not require a name. They are typically used for short-term operations and are written using the lambda
keyword.
1. Syntax of a Lambda Function
lambda arguments: expression
lambda
– Keyword to define a lambda function.arguments
– Input parameters (like normal function parameters).expression
– A single expression evaluated and returned.
Example: Lambda Function for Squaring a Number
square = lambda x: x * x
print(square(4))
Output:
16
πΉ Key Differences from Regular Functions:
- No
def
keyword is used. - No return statement – The expression result is automatically returned.
- Concise – Usually written in a single line.
2. Using Lambda Functions with Multiple Arguments
Lambda functions can take multiple arguments, separated by commas.
Example: Adding Two Numbers
add = lambda a, b: a + b
print(add(10, 20))
Output:
30
Example: Finding the Maximum of Two Numbers
maximum = lambda a, b: a if a > b else b
print(maximum(10, 20))
Output:
20
3. Use Cases of Lambda Functions
Lambda functions are useful when short, simple functions are needed without defining a full function.
3.1 Using Lambda with map()
The map()
function applies a function to each element of a list.
Example: Doubling Each Element in a List
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
Output:
[2, 4, 6, 8, 10]
3.2 Using Lambda with filter()
The filter()
function selects elements that satisfy a condition.
Example: Filtering Even Numbers
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Output:
[2, 4, 6]
3.3 Using Lambda with reduce()
The reduce()
function reduces a list into a single value by applying a function repeatedly. It is available in the functools
module.
Example: Finding the Sum of All Elements
from functools import reduce
numbers = [10, 20, 30, 40, 50]
total_sum = reduce(lambda x, y: x + y, numbers)
print(total_sum)
Output:
150
4. Lambda Functions with Conditional Expressions
Lambda functions can also include conditional expressions (like if-else
).
Example: Checking if a Number is Even or Odd
even_or_odd = lambda x: "Even" if x % 2 == 0 else "Odd"
print(even_or_odd(5))
print(even_or_odd(8))
Output:
Odd
Even
Example: Returning the Larger of Two Numbers
greater = lambda a, b: a if a > b else b
print(greater(10, 25))
Output:
25
5. Assigning Lambda Functions to Variables
You can assign a lambda function to a variable and use it multiple times.
multiply = lambda x, y: x * y
print(multiply(5, 10)) # Output: 50
print(multiply(3, 7)) # Output: 21
6. Nesting Lambda Functions
Lambda functions can be nested inside other functions.
Example: Nested Lambda in a Function
def power(n):
return lambda x: x ** n
square = power(2)
cube = power(3)
print(square(4)) # Output: 16
print(cube(2)) # Output: 8
7. Sorting Using Lambda Functions
Lambda functions are often used as keys in sorting.
Example: Sorting a List of Tuples by Second Value
students = [("Alice", 25), ("Bob", 22), ("Charlie", 23)]
students_sorted = sorted(students, key=lambda student: student[1])
print(students_sorted)
Output:
[('Bob', 22), ('Charlie', 23), ('Alice', 25)]
8. Lambda in List Comprehensions
Lambda functions can be used inside list comprehensions.
Example: Squaring Numbers Using List Comprehension with Lambda
numbers = [1, 2, 3, 4, 5]
squares = [(lambda x: x * x)(num) for num in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
9. Limitations of Lambda Functions
While lambda functions are useful, they have some limitations:
✅ Pros:
- Short and concise.
- Good for small, throwaway functions.
- Can be used inside other functions.
❌ Cons:
- Limited to a single expression (cannot include multiple lines).
- Less readable for complex operations.
- Cannot include statements like loops, assignments (
=
), orreturn
.
10. Regular Function vs. Lambda Function
Feature | Regular Function | Lambda Function |
---|---|---|
Definition | Uses def keyword |
Uses lambda keyword |
Number of lines | Can be multiple lines | Single-line expressions only |
Return statement | Explicit return needed |
Implicit return of expression |
Readability | Easier for complex logic | Suitable for short tasks |
Example | def add(a, b): return a + b |
lambda a, b: a + b |
Conclusion
- Lambda functions are short, single-expression functions defined using the
lambda
keyword. - They are useful in map(), filter(), and reduce() functions.
- They can be assigned to variables, nested, and used in sorting or list comprehensions.
- While convenient, lambda functions cannot include multiple statements and are best suited for simple operations.
Practice Problems on Lambda Functions π
Try solving these problems to reinforce your understanding of lambda functions in Python.
1. Basic Lambda Function (Easy)
π Problem:
Write a lambda function that takes a number as input and returns its cube.
✅ Example:
cube = lambda x: x ** 3
print(cube(3)) # Output: 27
print(cube(5)) # Output: 125
πΉ Your Task: Implement a lambda function that returns the cube of a given number.
2. Even or Odd (Easy)
π Problem:
Create a lambda function to check if a given number is even or odd.
✅ Example:
even_or_odd = lambda x: "Even" if x % 2 == 0 else "Odd"
print(even_or_odd(4)) # Output: Even
print(even_or_odd(7)) # Output: Odd
πΉ Your Task: Modify the function to check if a number is positive, negative, or zero.
3. Find Maximum (Easy)
π Problem:
Create a lambda function that takes two numbers and returns the maximum.
✅ Example:
maximum = lambda a, b: a if a > b else b
print(maximum(10, 20)) # Output: 20
πΉ Your Task: Modify it to find the maximum of three numbers.
4. Square and Cube Using map()
(Medium)
π Problem:
Use the map()
function with a lambda function to compute the square and cube of each number in a list.
✅ Example:
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
cubes = list(map(lambda x: x**3, numbers))
print(squares) # Output: [1, 4, 9, 16, 25]
print(cubes) # Output: [1, 8, 27, 64, 125]
πΉ Your Task: Modify the function to double each number in the list.
5. Filter Prime Numbers (Medium)
π Problem:
Write a lambda function to filter out prime numbers from a list.
✅ Example:
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10]
prime_check = lambda x: all(x % i != 0 for i in range(2, int(x**0.5) + 1)) and x > 1
primes = list(filter(prime_check, numbers))
print(primes) # Output: [2, 3, 5, 7]
πΉ Your Task: Modify it to filter out even numbers instead.
6. Sum of Digits Using reduce()
(Medium)
π Problem:
Write a lambda function with reduce()
to find the sum of digits of a number.
✅ Example:
from functools import reduce
num = 1234
sum_digits = reduce(lambda x, y: int(x) + int(y), str(num))
print(sum_digits) # Output: 10 (1+2+3+4)
πΉ Your Task: Modify the function to multiply all digits of the number.
7. Sorting List of Tuples (Hard)
π Problem:
You are given a list of tuples containing names and scores. Write a lambda function to sort the list by scores in descending order.
✅ Example:
students = [("Alice", 85), ("Bob", 90), ("Charlie", 78)]
students_sorted = sorted(students, key=lambda x: x[1], reverse=True)
print(students_sorted)
# Output: [('Bob', 90), ('Alice', 85), ('Charlie', 78)]
πΉ Your Task: Modify it to sort by name alphabetically instead.
8. Palindrome Checker (Hard)
π Problem:
Write a lambda function to check if a given string is a palindrome.
✅ Example:
is_palindrome = lambda s: s == s[::-1]
print(is_palindrome("radar")) # Output: True
print(is_palindrome("hello")) # Output: False
πΉ Your Task: Modify it to check for case-insensitive palindromes (e.g., "Madam" should return True
).
9. Generate Fibonacci Sequence (Hard)
π Problem:
Use a lambda function inside map()
to generate the first n
Fibonacci numbers.
✅ Example:
from functools import reduce
fib = lambda n: reduce(lambda x, _: x + [x[-1] + x[-2]], range(n-2), [0, 1])
print(fib(10))
# Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
πΉ Your Task: Modify the function to return only even Fibonacci numbers.
Bonus Challenge π
10. Find Anagrams Using Lambda (Very Hard)
π Problem:
Write a lambda function to check if two strings are anagrams (contain the same letters in different orders).
✅ Example:
is_anagram = lambda s1, s2: sorted(s1) == sorted(s2)
print(is_anagram("listen", "silent")) # Output: True
print(is_anagram("hello", "world")) # Output: False
πΉ Your Task: Modify it to be case-insensitive.