In Python, map() is a built-in function used to apply function to each item in an iterable (such as a list, tuple, or string) and return a new iterable containing the results.
The map() function takes two arguments: function to apply and the iterable to apply it to.
map(function, iterable)
`map` function accepts the first argument as a function named `double` and the second argument `numbers` list. Iterating over each item from the list multiply by 2 and return a new iterable containing the result.
# Define a function to double a number def double(x): return x * 2 # Apply the double function to each item in a list using map numbers = [1, 2, 3, 4, 5, 6, 7, 8] result = map(double, numbers) print(list(result)) # Output: [2, 4, 6, 8, 10, 12, 14, 16]
`map` function accepts the first argument as an anonymous or lambda function and the second argument `numbers` list. Iterate over each item from the list and multiply by `power` of 2 and return a new iterable containing a result.
# Apply a lambda function to each item in a list using map numbers = [1, 2, 3, 4, 5, 6, 7, 8] pow_numbers = map(lambda x: x ** 2, numbers) print(list(pow_numbers)) # Output: [1, 4, 9, 16, 25, 36, 49, 64]
`map` function accept first argument as add function, second and third arguments as `numbers1` list, `numbers2` list respectively.
Looping over on both list simultaneously while iterating on each item from lists its adding both item with each other and returning a new iterable containing a result.
# Define a function to add two numbers def add(x, y): return x + y # Apply the add function to each pair of items from two lists using map numbers1 = [1, 2, 3] numbers2 = [4, 5, 6] sums = map(add, numbers1, numbers2) print(list(sums)) # Output: [5, 7, 9]
Map with string, map() function first argument `string object` and second argument as `string text`.
# Convert each character of a string to uppercase using map text = "hello" uppercase_text = map(str.upper, text) print(list(uppercase_text)) # Output: ['H', 'E', 'L', 'L', 'O']
The map() function returns an iterator, so we need to convert it to a list or iterate over it to access the results.
If the function argument is None, "map()" returns an iterator that applies the identity function to each item in the iterable, effectively returning the iterable unchanged.
"map()" can accept multiple iterable arguments, but the function must have a corresponding number of arguments to apply to each item in the iterable.
"map()" is often used in conjunction with lambda functions for quick data transformations.