Kodeclik Blog
About
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.
Popular Classes
Scratch Coding
Minecraft Coding
TinkerCAD
Roblox Studio
Python for Kids
Javascript for Kids
Pre-Algebra
Geometry for Kids
Copyright @ Kodeclik 2024. All rights reserved.
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:
This gives the output:
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.
This produces the output:
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:
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:
This gives:
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:
This produces:
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:
This produces:
You can use a formatted print to restrict each output to have a max of 2 digits after the decimal (for instance).
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.
This produces the same output as before:
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:
This produces the output:
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.
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:
This outputs:
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:
The output is now:
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:
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:
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:
This gives, as expected:
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:
The output will be:
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:
This outputs:
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:
This outputs:
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.
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.
mylist = [1,3,4,5,6]
print(mylist)
[1, 3, 4, 5, 6]
mylist = [1,3,4,5,6]
squaredlist = []
for e in mylist:
squaredlist.append(e*e)
print(squaredlist)
[1, 9, 16, 25, 36]
def square(x):
return(x*x)
mylist = [1,3,4,5,6]
squaredlist = map(square,mylist)
def square(x):
return(x*x)
mylist = [1,3,4,5,6]
squaredlist = map(square,mylist)
print(squaredlist)
<map object at 0x7ff6d1abd790>
def square(x):
return(x*x)
mylist = [1,3,4,5,6]
squaredlist = map(square,mylist)
print(list(squaredlist))
[1, 9, 16, 25, 36]
def f2c(temp):
return(5*(temp-32)/9)
fahrenheit = [60,75,80,95]
celsius = map(f2c,fahrenheit)
print(list(celsius))
[15.555555555555555, 23.88888888888889, 26.666666666666668, 35.0]
fahrenheit = [60,75,80,95]
celsius = map(lambda x: 5*(x-32)/9,fahrenheit)
print(list(celsius))
[15.555555555555555, 23.88888888888889, 26.666666666666668, 35.0]
# 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))
[1.0, 4.0, 1.5, 12.5]
mystring = 'magic'
result = map(lambda x: chr(ord(x) + 1), mystring)
print(list(result))
['n', 'b', 'h', 'j', 'd']
mystring = 'magic'
result = map(lambda x: chr(ord(x) + 1), mystring)
print(''.join(list(result)))
nbhjd
magic = "abracadabra"
print(list(map(list,magic)))
[['a'], ['b'], ['r'], ['a'], ['c'], ['a'], ['d'], ['a'], ['b'], ['r'], ['a']]
magicwords = ["abracadabra","presto","open sesame"]
print(list(map(list,magicwords)))
[['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']]
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'))
brcdbr
def remove_vowel(s):
if s in ['a','e','i','o','u']:
return ('')
else:
return(s)
print(list(map(remove_vowel,'abracadabra')))
['', 'b', 'r', '', 'c', '', 'd', '', 'b', 'r', '']
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))
brcdbr