The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.
Syntax:
map(function, iterables)
function - The function to execute for each item.
iterables - A sequence, collection or an iterator object. You can send as many iterables as you like, just make sure the function has one parameter for each iterable.
advantage of map:
Memory Efficiency (Lazy Evaluation)
Faster Execution Speed
Cleaner, More Concise Code
# Using a standard for loop (4 lines)
words = ["apple", "banana", "cherry"]
lengths = []
for w in words:
lengths.append(len(w))
# Using map() (1 line)
lengths = list(map(len, words))
Built-in Support for Multiple Iterables
a = [1, 2, 3]
b = [10, 20, 30]
totals = list(map(lambda x, y: x + y, a, b)) # Output: [11, 22, 33]
Top comments (0)