Map

Imagine yourself creating an square function. You start typing out your usual single character parameter x and you simply return x**2. Great! You followed one of the rules that we mentioned earlier — create functions with a single task. Moments later your boss shows up, sheds a tear at how productive you are and feels confident in giving you a larger task. He ask’s you now to take an list of data and apply your function to each and every item within that list. Now you might attempt to use a list comprehension in order to accomplish this task, which is perfectly fine, but remember we want to keep our tasks within functions as much as possible. This is where the map function comes in.

# The square function

def square(x):

return x**2 list_of_numbers = [1,2,3,4,5] # our bosses list of numbers # The traditional way you were thinking before I entered your conscious through this blog post and told you about the use of the map function (if you hadn't already known about the map function....let's just stick with the story...) list_of_numbers = [square(number) for number in list_of_numbers] # The use of the amazing map function map(square,list_of_numbers) # Yes, it's as simple as that. Look at how short that is. *Sheds tear*

What the map function does is take a function as a parameter and an iterable and then applies the function to each and every member of that iterable. It’s just like using a list comprehension except you don’t have to type out any brackets (seriously, those keys are to the far left of your fingers. Who in the world put them there? (ﾉಥ益ಥ）ﾉ ┻━┻)