# Traditional function
def square(a):
return a * a
# Using the function
res = square(6)
print(res)
Output:36
This can be rewritten using a lambda function:# Lambda function
f = lambda a: a * a
# Using the lambda function
res = f(6)
print(res)
Output:36
As you can see, the lambda function reduces the code significantly while retaining clarity.lambda arguments: expression
return
keyword.map()
, filter()
, and others that expect a function as an argument. They are best suited for small, temporary tasks within larger operations.map()
map()
function applies a given function to each item in an iterator (e.g., a list). Here’s how it works with a lambda function:# User-defined function
list1 = ["FACE Prep", "Python"]
res = map(len, list1)
print(list(res))
Output:[9, 6]
list1 = ["FACE Prep", "Python"]
res = map(lambda a: len(a), list1)
print(list(res))
Output:[9, 6]
Visual Suggestion: Add an illustration showing the mapping process applied to a list.filter()
filter()
function extracts elements from an iterator based on a condition. Here’s how you can use it:# User-defined function
def is_even(a):
return a % 2 == 0
list1 = [12, 5, 18, 22, 97, 44]
res = filter(is_even, list1)
print(list(res))
Output:[12, 18, 22, 44]
list1 = [12, 5, 18, 22, 97, 44]
res = filter(lambda a: a % 2 == 0, list1)
print(list(res))
Output:[12, 18, 22, 44]
Visual Suggestion: Display a diagram with an input list and the filtered output.f = lambda a, b: a + b
res = f(6, 4)
print(res)
Output:10
f = lambda a: format(a, 'x')
res = f(12)
print(res)
Output:c
Visual Suggestion: Show a simple flowchart converting inputs to outputs for lambda functions.