The map()
function applies a given function to all items in an iterable (like a list or tuple) and returns a map object (which is an iterator). It's commonly used for transforming data.
map(function, iterable)
# 1. Using map with a built-in function
numbers = [1, 2, 3, 4]
squares = map(pow, numbers, [2]*len(numbers))
print(list(squares)) # Output: [1, 4, 9, 16]
# 2. Using map with a lambda function
numbers = [1, 2, 3, 4]
doubled = map(lambda x: x * 2, numbers)
print(list(doubled)) # Output: [2, 4, 6, 8]
# 3. Converting strings to integers
str_nums = ["1", "2", "3"]
int_nums = map(int, str_nums)
print(list(int_nums)) # Output: [1, 2, 3]
# 4. Applying map to multiple iterables
a = [1, 2, 3]
b = [4, 5, 6]
result = map(lambda x, y: x + y, a, b)
print(list(result)) # Output: [5, 7, 9]
# 5. Using map to strip whitespace from strings
names = [" Alice ", " Bob ", " Charlie "]
clean_names = map(str.strip, names)
print(list(clean_names)) # Output: ['Alice', 'Bob', 'Charlie']