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()

Copy

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()

Copy

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()

Copy

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

Copy


5. Mapping to Get Squares of Numbers

Copy


6. Filtering Palindromes

Copy


7. Combining Two Lists with map()

Copy


8. Filtering Positive Numbers

Copy


9. Applying a Conditional Operation with map()

Copy


10. Filtering and Mapping in a Single Expression

Copy

Last updated