119. Lambda Functions in map and filter

Here are 10 Python snippets showcasing the use of lambda functions with map() and filter() for concise transformations:


1. Doubling Numbers in a List with map()

numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)  # Output: [2, 4, 6, 8, 10]

2. Converting a List of Strings to Integers with map()

strings = ["1", "2", "3", "4"]
integers = list(map(lambda x: int(x), strings))
print(integers)  # Output: [1, 2, 3, 4]

3. Filtering Even Numbers with filter()

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # Output: [2, 4, 6]

4. Filtering Strings with a Specific Length

words = ["apple", "bat", "cat", "elephant"]
filtered_words = list(filter(lambda x: len(x) == 3, words))
print(filtered_words)  # Output: ['bat', 'cat']

5. Mapping to Get Squares of Numbers


6. Filtering Palindromes


7. Combining Two Lists with map()


8. Filtering Positive Numbers


9. Applying a Conditional Operation with map()


10. Filtering and Mapping in a Single Expression

Last updated