Kodeclik Blog
Python Map Function
In Python, the map function is a powerful tool that allows you to apply a function to each item in an iterable (like a list) and return a map object. This built-in function simplifies the process of transforming data and can be particularly useful when combined with lambda functions. In this guide, we’ll explore how the map function works, how to use it with lambda expressions, and how to convert the map object into a list.
Python’s map function applies a function to each item in an iterable, and returns a 'mapped' iterable. Let us assume you have a list of numbers:
mylist = [1,3,4,5,6]
print(mylist)
This gives the output:
[1, 3, 4, 5, 6]
Exampe 1: Square the elements in a list
Let us suppose you want to square each element in a list and return a new list. We usually do it with a for loop.
mylist = [1,3,4,5,6]
squaredlist = []
for e in mylist:
squaredlist.append(e*e)
print(squaredlist)
This produces the output:
[1, 9, 16, 25, 36]
An easier way to do it is using the map() function. With map we view the function as a “hammer” and apply it uniformly to every element of the list.
In our case, the hammer is the square function. map() takes as input the hammer function and the list that you want to apply it to, like so:
def square(x):
return(x*x)
mylist = [1,3,4,5,6]
squaredlist = map(square,mylist)
See how elegant this notation is? The functionality of squaring a number is factored out in the function square(x). The map function applies it uniformly to each element of the list.
Let us try to print the list we just created:
def square(x):
return(x*x)
mylist = [1,3,4,5,6]
squaredlist = map(square,mylist)
print(squaredlist)
This gives:
<map object at 0x7ff6d1abd790>
Woah! What does this mean? The output above says that squaredlist is a mapped object (an iterable) but it is computed lazily, only on demand, when you really need it. For this purpose, we use the list() constructor:
def square(x):
return(x*x)
mylist = [1,3,4,5,6]
squaredlist = map(square,mylist)
print(list(squaredlist))
This produces:
[1, 9, 16, 25, 36]
Example 2: Convert temperatures
Because the map function factorizes out the operation from the iterable it is very easy to adapt the above code to do a different operation. For instance, suppose I want to take a list of temperatures in fahrenheit and convert them to celsius:
def f2c(temp):
return(5*(temp-32)/9)
fahrenheit = [60,75,80,95]
celsius = map(f2c,fahrenheit)
print(list(celsius))
This produces:
[15.555555555555555, 23.88888888888889, 26.666666666666668, 35.0]
You can use a formatted print to restrict each output to have a max of 2 digits after the decimal (for instance).
Example 3: Using lambda expressions in place of defined functions
If you do not desire or need to define a function for use in map(), you can substitute a lambda function that defines the function without naming it.
fahrenheit = [60,75,80,95]
celsius = map(lambda x: 5*(x-32)/9,fahrenheit)
print(list(celsius))
This produces the same output as before:
[15.555555555555555, 23.88888888888889, 26.666666666666668, 35.0]
Example 4: Multiple iterables
The map() function is not restricted to using only one list as input. If your function can be defined as a systematic iteration over multiple lists you can use map for the same purpose. For instance assume you have a list of prices of fruits and another list of amount of fruit:
# fruits: apples, oranges, bananas, pears
fruitamounts = [1,2,3,5]
fruitunitprices = [1.00,2.00,0.50,2.50]
fruitprices = map(lambda x, y: x*y,fruitamounts, fruitunitprices)
print(list(fruitprices))
This produces the output:
[1.0, 4.0, 1.5, 12.5]
Note that in the above code we are using the function with two lists and the corresponding elements of the lists are multiplied to yield the prices.
Exampe 5: Strings
Because strings are also iterables in Python, we can apply map() over a string and it will consistently apply your given function on each element of the string. For instance, we can use the function to take a string and encode it into a secret representation by simply incrementing each character's ascii value by 1:
mystring = 'magic'
result = map(lambda x: chr(ord(x) + 1), mystring)
print(list(result))
This outputs:
['n', 'b', 'h', 'j', 'd']
Note that ‘m’ has been transformed to ‘n’, ‘a’ has been transformed to ‘b’, and so on.
The problem with this program is that the result is not a string anymore. We can use Python’s join() function to accomplish convert the resulting list back to a function:
mystring = 'magic'
result = map(lambda x: chr(ord(x) + 1), mystring)
print(''.join(list(result)))
The output is now:
nbhjd
Example 6: Using with list()
A cute use of map() happens when list() is the function being mapped over a list. Note that list() takes an iterable and constructs a list out of it. And recall that strings are also iterables. So you can take a string and make each element of the string to form a list.
Take the following piece of code:
magic = "abracadabra"
print(list(map(list,magic)))
This seems a bit complicated but let us take it step by step from the innermost construct. list() is a function that takes an iterable and constructs a list out of its elements. The use of map() above allows us to take each element of the string and make it into a list (a singleton list containing only one element). We then use another list outside to be able to print and view the results:
[['a'], ['b'], ['r'], ['a'], ['c'], ['a'], ['d'], ['a'], ['b'], ['r'], ['a']]
So this above code snippet takes a string and makes it a list of lists. Of course this example does not really make use of the power of the map() function because our list has only one element. Here is an example with a longer input list:
magicwords = ["abracadabra","presto","open sesame"]
print(list(map(list,magicwords)))
This gives, as expected:
[['a', 'b', 'r', 'a', 'c', 'a', 'd', 'a', 'b', 'r', 'a'], ['p', 'r', 'e', 's', 't', 'o'], ['o', 'p', 'e', 'n', ' ', 's', 'e', 's', 'a', 'm', 'e']]
Example 7: Creating license plate suggestions
Let us write a program to create license plate suggestions. License plate names need to be short but still recognizable. One way to create short strings is to remove the vowels in your string. Here’s how we might typically write such a function and use it:
def remove_vowels(s):
output = ''
for i in s:
if i not in ['a','e','i','o','u']:
output = output + i
return(output)
print(remove_vowels('abracadabra'))
The output will be:
brcdbr
Note that we haven’t used map() in this example. Let us remedy that. We will first use a function to remove a single vowel (character) and then apply it over a string iterable:
def remove_vowel(s):
if s in ['a','e','i','o','u']:
return ('')
else:
return(s)
print(list(map(remove_vowel,'abracadabra')))
This outputs:
['', 'b', 'r', '', 'c', '', 'd', '', 'b', 'r', '']
The problem with this is that the result is not a string anymore. We will use Python’s join() function as before to accomplish this:
def remove_vowel(s):
if s in ['a','e','i','o','u']:
return('')
else:
return(s)
newlist = list(map(remove_vowel,'abracadabra'))
print(''.join(newlist))
This outputs:
brcdbr
So what have we learnt in this blog post? Python’s map() function is a very handy approach to uniformly applying a procedure/function on an iterable (e.g., a list or a string) without explicitly using a for loop. A very closely related Python function is the reduce() function.
Summary
The map function in Python is a versatile and powerful tool for applying a function to each item in an iterable. Whether you use it with built-in functions, lambda expressions, or user-defined functions, it provides a streamlined way to perform data transformations. Remember to convert the map object to a list or another suitable data structure to access the results.
By mastering the map function and its various applications, you can simplify your data processing tasks and write cleaner, more efficient code. Happy coding!
If you liked the functional programming style described in this blog, checkout how to generate all permutations of a given string in Python.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.