Practical Use Cases and Examples
Sorting a List of Dictionaries
Suppose you have a list of dictionaries representing employee data, and you want to sort the list based on the employee's age.
employees = [
{"name": "Alice", "age": 30, "salary": 50000},
{"name": "Bob", "age": 25, "salary": 45000},
{"name": "Charlie", "age": 35, "salary": 55000},
{"name": "David", "age": 28, "salary": 48000}
]
sorted_employees = sorted(employees, key=lambda x: x["age"])
print(sorted_employees)
Output:
[{'name': 'Bob', 'age': 25, 'salary': 45000},
{'name': 'David', 'age': 28, 'salary': 48000},
{'name': 'Alice', 'age': 30, 'salary': 50000},
{'name': 'Charlie', 'age': 35, 'salary': 55000}]
Filtering a List of Strings by Length
You have a list of strings and you want to filter out the strings that are longer than a certain length.
words = ["apple", "banana", "cherry", "date", "elderberry", "fig"]
short_words = list(filter(lambda x: len(x) <= 5, words))
print(short_words)
Output:
['apple', 'banana', 'date', 'fig']
You have a list of numbers and you want to create a new list where each number is multiplied by 2.
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print(doubled_numbers)
Output:
[2, 4, 6, 8, 10]
Combining Lambda with List Comprehension
You can use lambda functions in combination with list comprehensions to create more complex transformations.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
doubled_even_numbers = [x * 2 for x in filter(lambda x: x % 2 == 0, numbers)]
print(doubled_even_numbers)
Output:
[4, 8, 12, 16, 20]
These examples demonstrate the versatility of lambda functions in working with lists and how they can simplify common list operations. By understanding and applying lambda functions, you can write more concise and expressive Python code.