Map is a built-in function that takes a function and an iterable as arguments and applies the function to each element in the iterable.
map(function, iterable)
An iterable could be an object which can be iterated, such as — a list, tuple, etc.
The map function can be used to replace loops that are used to perform some operation on each element in a list. Here’s an example:
Example 1: Finding the square of numbers
## Traditional Loop
nums = (1, 3, 4, 5, 6, 7)
def square_numbers(nums):
squares = []
for num in nums:
squares.append(num**2)
## One-liner
squares = list(map(lambda x: x**2, nums))
Example 2: Consider the scenario where we have a list of sentences and want to count the number of words in each sentence. We can use a multi-line loop to achieve this as follows:
## Traditional Loop
sentences = ['This is the first sentence.',
'And this is the second sentence.',
'Finally, the third sentence.']
word_counts = []
for sentence in sentences:
words = sentence.split()
word_count = len(words)
word_counts.append(word_count)
### line liner
word_counts = list(map(lambda sentence: len(sentence.split()), sentences))