What is Anonymous (Lambda) Functions in Python with syntax and example.
Lambda functions are used for creating short, simple operation functions and are useful when you need a quick function for a one-time use.
lambda functions are also called anonymous functions because they don’t have a name like regular functions.
Syntax:
lambda arguments: expression
- Arguments: the parameters used within the lambda expression.
- Expression: Operation or functionality of the function.
Example: Create a function to add two numbers using the lambda function.
Solution:
sumthem = lambda a, b : print(a+b)
sumthem(10, 20)
Output:
30
Example: example that uses a lambda function to double a number:
Solution:
double = lambda x: x * 2
print(double(5))
Output:
10
How to apply Conditional Expressions in lambda function.
Lambda functions can be useful for small conditional expressions in data structures.
Syntex:
lambda arguments : "success statment" if condation else "fail statment"
Example:
get_status = lambda x: "Pass" if x >= 50 else "Fail"
print(get_status(70))
Output:
Pass
What are the use cases of lambda functions in Python?
Here are some common use cases:
- map()
- filter()
- reduce()
How to use map() function with lambda?
map() applies a function to every item in an iterable (e.g., a list) and returns a new object. It basically helps to modify data.
Syntax:
map(lambda_function, data)
Example:
numbers = [1, 2, 3, 4]
doubled = map(lambda x: x * 2, numbers)
print(doubled)
Note : Always remember map() function always return the output in the object format, so you have to do type casting to get the data.
Output:
<map object at 0x7b1327fd9ab0>
so:
numbers = [1, 2, 3, 4]
doubled = map(lambda x: x * 2, numbers)
print(list(doubled))
Output:
[2, 4, 6, 8]
How to use filter() function with lambda?
filter() returns items in an iterable that match a condition.
Syntax:
filter(lambda_function, dataset)
Example:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
Note : Always remember filter() function always return the output in the object format, so you have to do type casting to get the data.
Output:
[2, 4, 6]
How to use reduce() function with lambda?
reduce() is a function from functools that applies a rolling computation to items in an iterable.
Syntax:
from functools import reduce
reduce(lambda_function, dataset)
Example:
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)
Output:
24
Unique interview questions covering lambda functions, map(), filter(), reduce(),
Question 1. How can you use map() with multiple iterables and a lambda function?
Answer: The map() function can process multiple iterables if the lambda function takes more than one argument. Each iterable provides one argument to the lambda function in sequence.
Example:
nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
result = list(map(lambda x, y: x + y, nums1, nums2))
print(result)
Output:
[5, 7, 9]
Question 2. Explain how to use filter() with multiple conditions in a lambda function.
Answer: You can combine multiple conditions using logical operators like and, or in a lambda function within filter().
Example:
nums = [10, 15, 20, 25, 30]
result = list(filter(lambda x: x % 2 == 0 and x > 15, nums))
print(result)
Output:
[20, 30]
Question 3. Can a lambda function inside reduce() keep track of the previous result? How?
Answer: Yes, reduce() naturally passes the cumulative result (or “accumulator”) to the lambda function, allowing it to "remember" previous results.
Example:
from functools import reduce
nums = [1, 2, 3, 4]
result = reduce(lambda acc, x: acc + x, nums)
print(result)
Output:
10
Question 4. How would you use map() to apply different operations on elements from two lists?
Answer: You can use map() with a lambda that conditionally applies different operations based on element values.
Example:
nums1 = [10, 20, 30]
nums2 = [1, 2, 3]
result = list(map(lambda x, y: x * y if x > y else x + y, nums1, nums2))
print(result)
Output:
[10, 40, 90]
Question 5. How can you use map() with a lambda function that returns multiple values for each element?
Answer: A lambda function can return a tuple or a list for each element, creating multiple outputs per element.
Example:
nums = [1, 2, 3]
result = list(map(lambda x: (x, x**2), nums))
print(result)
Output:
[(1, 1), (2, 4), (3, 9)]
Question 6. How can lambda functions with filter() be used to filter out None values?
Answer: By using a lambda function to filter out elements that are not None.
Example:
values = [None, 'hello', None, 'world']
result = list(filter(lambda x: x is not None, values))
print(result)
Output:
['hello', 'world']
Question 7. Explain how you would use a lambda function within map() to flatten a list of lists.
Answer: Use a lambda function to unpack each inner list and return its elements as single values.
Example:
lists = [[1, 2], [3, 4], [5, 6]]
result = list(map(lambda x: x[0] + x[1], lists))
print(result)
Output:
[3, 7, 11]
Question 8. How can map() and filter() be used together with a lambda to process data?
Answer: Use filter() first to select items based on a condition, then map() to transform the selected items.
Example:
nums = [1, 2, 3, 4, 5, 6]
result = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, nums)))
print(result)
Output:
[4, 8, 12]
Question 9. Can you use lambda functions with map() to process elements differently based on index position?
Answer: Yes, by using enumerate() with map() to include the index in the lambda function.
Example:
nums = [10, 20, 30]
result = list(map(lambda i_n: i_n[0] * i_n[1], enumerate(nums)))
print(result)
Output:
[0, 20, 60]
Question 10. How do you use reduce() to find the longest string in a list?
Answer: reduce() can be used with a lambda to compare lengths and keep the longest string.
Example:
from functools import reduce
words = ["apple", "banana", "cherry"]
longest = reduce(lambda acc, x: x if len(x) > len(acc) else acc, words)
print(longest)
Output:
banana
Question 11. How can you create a dictionary from two lists using map() and lambda?
Answer: Use map() with zip() to create key-value pairs and then convert them to a dictionary.
Example:
keys = ['a', 'b', 'c']
values = [1, 2, 3]
result = dict(map(lambda x_y: (x_y[0], x_y[1]), zip(keys, values)))
print(result)
Output:
{'a': 1, 'b': 2, 'c': 3}
Question 12. How do you use filter() to extract only uppercase words from a list?
Answer: Use filter() with a lambda function that checks if each word is uppercase.
Example:
words = ["Hello", "WORLD", "Python", "CODING"]
result = list(filter(lambda x: x.isupper(), words))
print(result)
Output:
['WORLD', 'CODING']
Question 13. How can you use reduce() to count occurrences of each element in a list?
Answer: You can use reduce() with a lambda function to update a dictionary with counts.
Example:
from functools import reduce
items = ['a', 'b', 'a', 'c', 'b', 'a']
counts = reduce(lambda acc, x: acc.update({x: acc.get(x, 0) + 1}) or acc, items, {})
print(counts)
Output:
{'a': 3, 'b': 2, 'c': 1}
Tags:
Leave a comment
You must be logged in to post a comment.