Beginner LevelPython
What are Lambda functions and how do you use them with map(), filter(), and sorted()?
❓ Interview Prompt: Explain anonymous inline functions (`lambda arguments: expression`), syntax limitations (single expression), and usage in sorting keys.
A Lambda Function is a small, anonymous inline function defined with the 'lambda' keyword:
Syntax:
'lambda arguments: expression'
Characteristics:
•
Can take any number of arguments, but can contain only one single expression (no multi-line statements or 'return' keywords allowed).
•
Primary Use Case: Passing quick callback functions into higher-order functions like 'map()', 'filter()', and 'sorted(key=...)'.
Code Implementation Example
python
users = [
{'name': 'Alice', 'score': 85},
{'name': 'Bob', 'score': 92},
{'name': 'Charlie', 'score': 78}
]
# Sort list of dicts by 'score' using lambda key
sorted_users = sorted(users, key=lambda u: u['score'], reverse=True)
print(sorted_users[0]['name']) # 'Bob'
# Filter even numbers using lambda
evens = list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6]))💡Sorting dictionaries and filtering lists using lambda callbacks.
🎯 Interview Key Takeaway
Use lambda functions for short, one-liner callback expressions, especially for sorted() key parameters.
#Lambda#Anonymous Functions#map#filter#sorted#Beginner
Back to all Python Questions→