The map function applies a supplied function to the elements in a sequence. The syntax is as follows:
map(function, sequence)
In return, the map sends a list of the sequences transformed by the function sent in. An easy, practical example to cover is conversions. We can convert the items in a sequence to what we want to, without leaving the list, with the map() function. The function we write will not take the sequence as a whole. You must write the function as if you are taking a single element from the sequence.
Example 1 Transforming a sequence of day values into hours.
In [5]:
# Function to apply
def days(hour):
return hour/24
# Sequence to transform
hour_list = [4.0, 24.0, 47, 72.0]
# Map
days_list = list(map(days, hour_list))
In [8]:
print(days_list)
It's a great time to start using lambdas. Lambda expressions were made for operations like the map() function. Let's try it out in the next example.
Example 2 You have a database of male names, and you need to send letters out to said people. Add the prefix "Mr." to every man's name.
In [10]:
# Sequence to transform
male_names = ["Rick", "Rocky", "Charles", "Peter"]
# Map
mr_male_names = list(map(lambda name: "Mr. " + name, male_names))
In [11]:
print(mr_male_names)
You can apply map() to multiple sequences. A few good, immediate examples are combining sequences in some shape or form. Imagine you have the total scores of 3 players from 3 rounds, where each player X score is item X. If we want the total score, we have to add them all up using bracket notation.
In [15]:
# [player1score, player2score, player3score]
round_1 = [8, 6, 9]
round_2 = [5, 7, 7]
round_3 = [8, 9, 6]
round_totals = list(map(lambda r_1, r_2, r_3: r_1 + r_2 + r_3, round_1, round_2, round_3))
In [16]:
print(round_totals)