They are designed to manipulate collections of data concisely.
A
lambdafunction is a small, anonymous, one-line function that can take any number of arguments but can only have a single expression.
users = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
# Sorting a list of dictionaries by a specific key
sorted_users = sorted(users, key=lambda user: user["age"])
# user["age"] - It tells Python: "Look inside each dictionary, grab the value associated with the 'age' key, and use that number to determine the sort order.
The
map()function applies a specific function to every item in an iterable (like a list) and returns an iterator.
# Good use case: You already have a function (e.g., str.upper)
words = ['apple', 'banana', 'cherry']
uppercase_words = list(map(str.upper, words))
# Avoid this: map + lambda
numbers = [1, 2, 3]
squared = list(map(lambda x: x**2, numbers))
# Do this instead (List Comprehension):
numbers = [1, 2, 3]
squared = [x**2 for x in numbers]
The filter() function extracts items from an iterable based on a condition (a function that returns True or False).
# Good use case: Removing None or empty values from a dataset
data = ['hello', '', 'world', None, 'python']
valid_data = list(filter(None, data)) # Removes Falsy values like '' and None
# Avoid this: filter + lambda
# evens = list(filter(lambda x: x % 2 == 0, numbers))
# Do this instead (List Comprehension):
evens = [x for x in numbers if x % 2 == 0]