Using lambda with map() is one of the most common patterns in Python. It allows you to apply a simple operation to every item in a list (or any iterable) without writing a full def function.
1. The Basic Syntax
The map() function takes two arguments:
- A function (What to do)
- An iterable (The data to do it to)
map(function, iterable)
2. Basic Example: Squaring Numbers
Suppose you have a list of numbers and you want to square each one:
numbers = [1, 2, 3, 4, 5]
# Using map with a lambda
squared = map(lambda x: x**2, numbers)
# map() returns an object, so we convert it to a list to see the result
print(list(squared))
# Output: [1, 4, 9, 16, 25]
3. Practical Example: Formatting Strings
You can use it to quickly clean up data, like capitalize a list of names:
names = ['carlos', 'wanda', 'rose']
# Apply .capitalize() to every name
clean_names = list(map(lambda name: name.capitalize(), names))
print(clean_names)
# Output: ['Carlos', 'Wanda', 'Rose']
4. Comparison: Regular Function vs. Lambda
If you used a regular function, it would look like this:
With def:
def double(n):
return n * 2
result = list(map(double, [1, 2, 3]))
With lambda (Quick and Clean):
result = list(map(lambda n: n * 2, [1, 2, 3]))
Why use them together?
- Conciseness: You don't have to define a function that you will only use once.
- Speed: For simple operations,
mapis written in C and is very efficient. - Functional Style: It makes your code look cleaner when performing simple transformations on data sequences.
Note: In modern Python, many developers prefer List Comprehensions instead of map for simple tasks because they can be easier to read:
squared = [x**2 for x in numbers] (This does the same thing as the map example above!)