Python map() function explained with examples

Introduction to python map function

The python map() function is a built-in function that allows us to process and transform the items in an iterable without using an explicitly for loop. This technique of loop without using explicit loop is called mapping in python. This function is useful when we need to apply a transformation function to each item in an iterable and transform them into a new interable one.

In this tutorial we will learn about the python map function, and how it works. We will also cover how we can transform, combine and replace python map() function.

Advertisement

 

Python map() syntax

map() passes each item of the iterable to the first argument ( function ). Second argument is iterable which is to be mapped. We can pass more than one iterable to the python map() function.

map(func, itera, …)

The operation that map() performs is commonly known as a mapping because it maps every item in an input iterable to a new item in a resulting iterable. To do that, python map() function applies a transformation function to all the items in the input iterable.

map(func, itera[, itera1, itera2,..., iteraN)

 

Example-1

See the example below which demonstrates the working of python map() function,  where we take a list of numeric values and transform it into a list containing the cube value of every number in the original list.

Let us first find cube values using python for loop.

# Creating list of number
numbers = [1, 2, 3, 4, 5]

# created new empty list
cube = []

# use for loop to iterate
for num in numbers:
    cube.append(num *num *num)

# printing list
print(cube)

Output:

[1, 8, 27, 64, 125]

You can see that we used a for loop to iterate in the above example. Now, let us implement the same login in the python map() function.

Advertisement
#  created function to calculate cube of number
def cube(number):

   # return cube
   return number * number * number

# list of number
numbers = [1, 2, 3, 4, 5]

# using map() to inerate
cube = map(cube, numbers)

# printing
print(list(cube))

Output:

[1, 8, 27, 64, 125]

cube() is a transformation function that maps a number to its cube value. The call to map() applies cube() to all of the values in numbers and returns an iterator that yields cube values. Then we call list() on map() to create a list object containing the square values.

You can see that, with a for loop, we need to store the whole list in our system’s memory. But with map(), we get items on demand, and only one item is in your system’s memory at a given time.

 

Example-2

Now, let us take one more example to see how we can use the python map() function to convert string numbers to an integer.

# list containing numbers as string
str_nums = ["4", "8", "6", "5", "3"]


# use map to convert str to int
int_nums = map(int, str_nums)

# printing the mapped in list
print(list(int_nums))

# printing the original list
print(str_nums)

Output:

[4, 8, 6, 5, 3]
['4', '8', '6', '5', '3']

Notice that we had successfully converted str to in using python map() function. Since map() returns an iterator (a map object), we need  to call list() so that we can exhaust the iterator and turn it into a list object.

 

Use python map() with other functions

We can use any kind of Python callable with the python map() function, with the condition that it takes an argument and returns a concrete and useful value. There are many built-in functions in python which take an argument and return concrete value, we can use them with the python map() function. See the example below.

# list of numbers
num = [-2, -1, 0, 1, 2]

# uses map and absolute function
abs_values = list(map(abs, num))

# printing absolute values
print(abs_values)

Output:

Advertisement
[2, 1, 0, 1, 2]

See one more example how we used python len() with map() function.

# list containing words
words = ["This", "is", "my", "Name"]

# created list
counted_list = list(map(len, words))

# print
print(counted_list)

Output:

[4, 2, 2, 4]

 

Python map() with lambda function

It is common to use lambda function with python map() function as the first argument. Lambda functions are handy when we need to pass an expression based function to map().  For example, see example below where we used lambda as the first argument in the python map() function to return cube values.

# list containing numbers
num_list = [1, 2, 3, 4, 5]

# lambda used as first argument in map
cube = list(map(lambda num: num * num * num, num_list))

# printing
print(cube)

Output:

[1, 8, 27, 64, 125]

Lambda functions are useful in python map() functions, as they play the role of first argument and process quickly and transform iterables.

 

Python map() and reduce() function

Reduce is a python function which is found inside the functools module. It is very useful when we need to apply a function to an iterable and reduce it to a single cumulative value. Such an operation is also known as reduction. The reduce () function takes two required arguments. First one is a function, that can be any python callable which accepts any two arguments and returns a value. Second argument is an iterable. The reduce() applies all functions to all the items in the iterable and finds cumulative value.

See example below to understand the working of reduce().

# importing reduce from functools
from functools import reduce

# defining lambda function
# using reduce function
print(reduce(lambda x,y:x+y, list(range(1,4))))

Output:

Advertisement
6

See one more example, how we can use python map and reduce functions together.

# importing reduce from functool
from functools import reduce

# creating lambda function
# using map to iterate
# and then used reduce funtion
print(reduce(lambda a, b: a, map(lambda a:a+a, (2,4,1))))

Output:

4

 

Python map() and filter() function

The filter() function filters the given sequence with the help of a function that tests each element in the sequence to be true or not. It takes two required arguments. The first one is a function, that tests if elements of an iterable return true or false

If None, the function defaults to Identity function which returns false if any elements are false. The second one is iterable which is to be filtered. It can be set, list or tuple.

See the example below which uses the filter function to print odd numbers less than 10.

# function that filters odd numbers less than 10
def odd(variable):
    odd_numbers = [1, 3, 5, 7, 9]
    if (variable in odd_numbers):
        return True
    else:
        return False   
# list to contain numbers
numbers =[]

# use for loop to create number list less than 10
for i in range(10):
    numbers.append(i) 

 # using filter function to print odd numbers
print(list(filter(odd, numbers)))

Output:

[1, 3, 5, 7, 9]

See one more example which uses map and filter together.

# tuple of numbers less than 10
number=(1,2,3,4,5,6,7,8,9,10)

# used map and fileter in one example
# filter provides only odd number, and map iterate over them to print
print(list(map(lambda x:x,filter(lambda x: (x%2!=0), (number)))))

Output:

[1, 3, 5, 7, 9]

 

Processing multiple inputs with python map

We can pass more than one iterable argument to the python map() function. If we pass more than one iterables to map() function, the transformation function will take as many arguments as iterables we passed in. And each iteration of map() will pass one value from each iterable as an argument to function. See the example below:

# list of numbers
first_list = [1, 2, 3]
second_list= [1, 2, 3]

# printing
print(list(map(pow, first_list, second_list)))

Output:

[1, 4, 27]

Now let's add more elements to our second_list and try to implement the same logic.

# list of numbers
first_list = [1, 2, 3]
second_list= [1, 2, 3, 4, 5, 6]

# printing
print(list(map(pow, first_list, second_list)))

Output:

[1, 4, 27]

Notice that the output didn't change. It is because the iteration stops at the end of the shortest iterable.

 

Transforming string iterables with python map

When we are working with iterables of string objects, we might be interested in transforming all the objects using some kind of transformation function. Python map() function can be our ally in such situations. The following sections will  see an examples of how to use map() to transform iterables of string objects.

Example-1: String method

We can use built-in functions provided by python to manipulate strings and transform them to a new string. If we are dealing with iterables of strings and need to apply the same transformation to other strings, we can then use the python map() function.  See example below:

# list of string
string_list = ["this", "is", "my", "name"]

# map function to capitalize
print(list(map(str.capitalize, string_list)))

# map function to convert to uppercase
print(list(map(str.upper, string_list)))

Output:

['This', 'Is', 'My', 'Name']
['THIS', 'IS', 'MY', 'NAME']

So far we have only used transformation that does not take any additional arguments. Like str.capitalizer() and str.upper(), these methods don't take any additional arguments. However, we can also use those methods that take additional arguments by default and the best example could be str.strip() method, which takes an options argument that removes whitespaces. See example below:

# list of string containing whitespaces
string_list = ["   this", "Is   ", "my", "  name"]

# applying map with additional argument
print(list(map(str.strip, string_list)))

Output:

['this', 'Is', 'my', 'name']

 

Example-2: Removing punctuation using python map

When we split text into words, punctuation marks also remain with words and sometimes we may not want those punctuation marks.  To deal with this problem, we can create a custom function that removes punctuation marks from a single word using regular expressions that match the most common punctuation marks. See the example below where we had used function sub() which is in re module of python’s standard library.

#  importing re module
import re

# function to remove punctuations
def remove_punctuation(word):
   return re.sub(r'[!?.:;,"()-]', "", word)

# printing word after removing punctuation
print(remove_punctuation("...Bashir??"))

Output:

Bashir

Now, we can use the same logic and iterate through many words and remove punctuation. We can use the python map() function to run the transformation on every word in text. See the example of how it works.

# importing re module
import re

# function to remove punctuation
def remove_punctuation(word):
  return re.sub(r'[!?.:;,"()-]', "", word)

# text with punctuation
text = """Hi!!, This is Bashir Alam!. Majoring in computer science :)"""

# this splits the words and store in words
words = text.split()

# map function takes each word and removes punctuation marks
print(list(map(remove_punctuation, words)))

Output:

['Hi', 'This', 'is', 'Bashir', 'Alam', 'Majoring', 'in', 'computer', 'science']

 

Transforming numeric iterables using python map()

The python map() function is also very useful when it comes to processing and transforming interables of numeric values. We can perform a variety of math operations using the python map() function.  In this section we will cover some examples related to processing and transforming iterable numeric values using python map() function.

 

Example-1: Using math operators in python map

We can use math operations to transform an iterable of numeric values and the most common example will be returning the square of value. In the following example, we will code a transformation function which takes a number as an argument and returns a square of it.

# created a function which return square
def square(x):
 return x * x

# list of numbers
numbers = [1, 2, 3, 4]

# calling function using python map
print(list(map(square, numbers)))

Output:

[1, 4, 9, 16]

There can be many math related examples of transformations that we can perform using the python map() function. We can import math modules and get access to functions like pow(), factorial(), sqrt(), sin() and cos().

 

Here is an example of using factorial() by importing a math module.

# importing math module
import math

# list of numbers
numbers = [1, 2, 3, 4]

# calling factorial function using map
print(list(map(math.factorial, numbers)))

Output:

[1, 2, 6, 24]

 

Example-2: Converting to numeric values using python map

While working with numeric values, we might come across a situation where our data will be saved as string. In such situations, we can use the python map() function to convert the string values to integers by iterating over each of them.  See the example below which uses the python map() function to convert string to numeric values.

 

# Convert to integer
print(list(map(int, ["1", "4", "3"])))

Output:

[1, 4, 3]

Similarly we can convert floats to integer values using the same logic. See example below:

# Convert to integer
print(list(map(int, [1.4, 3.4, 3.9])))

Output:

[1, 3, 3]

 

Alternatives to Python map function

So far we have seen how we can use the python map() function in different scenarios and how they can be useful to iterate over a list of items. However, list comprehension and generator expressions have become a natural replacement for map() in almost every use case. In this section we will see how we can use them in place of the python map() function.

 

Example-1: List comprehension replacing python map

The list comprehension always reads more clearly than the call to python map() function. Since list comprehensions are quite popular among Python developers, it’s common to find them everywhere. So, replacing a call to python map with a list comprehension will make your code look more familiar to other Python developers.

See example below, how we replaced python map with list comprehension.

# return square
def square(number):
    return number * number

# list of numbers
numbers = [1, 2, 3, 4]

# Using map()
print(list(map(square, numbers)))

# Using a list comprehension
print([square(x) for x in numbers])

Output:

[1, 4, 9, 16]
[1, 4, 9, 16]

If we compare both solutions, then we can say that list comprehension one is more readable because it reads like plain English. Moreover, list comprehension avoids the need to explicitly call list() as we did in map().

 

Example-2: Generator expressions replacing Python map

As we know, the python map() function  returns a map object, which is an iterator that yields items on demand. So, the natural replacement for map() is a generator expression because generator expressions also return generator

We can use generator expressions to write code that reads clearer than code that uses python map() function. See the following example below:

# Transformation function
# return square
def square(number):
    return number * number

# list of numbers
numbers = [1, 2, 3, 4]

# Using a generator expression
g_p_list = (square(x) for x in numbers)

print(g_p_list)

Output:

[1, 4, 9, 16]

When we look closely, we can find out that there is a tiny syntactical difference between a list comprehension and a generator expression. The first uses a pair of square brackets ([]) to delimit the expression while the generator expression uses a pair of parentheses(()).

 

Python map() vs starmap() function

starmp() is similar to the python map() function in the sense that it makes an iterator that computes the function using arguments obtained from the iterable. We mostly use starmap() instead of map() when argument parameters are already grouped in tuples from a single iterable. To use the starmap() function, first, we have to import the itertools module. While using starmap() function, make sure that Items inside the iterable should also be iterable. Otherwise, it will give a TypeError.

See the following example of how we used starmap() to add numbers from a list of tuples.

# importing starmap from intertools
from itertools import starmap

# list of tuples containing number
number = [(1, 4), (5, 6), (10, 2)]

# user defined function to add two numbers
def addition(a, b):
    return a + b

# using starmap function
m = starmap(addition, number)

# Converting map object to list using list() and printing
print(list(m))

Output:

[5, 11, 12]

Now see the following example where we used both map() and starmap() to find the power of a given value. See the difference in syntax of both functions.

# importing intertools
import itertools

# using pow() inside starmp()
# takes list of tuples

print(list(itertools.starmap(pow,[(2,2),(3,3),(4,4)])))

# map() to give the same output
print(list(map(pow,[2,3,4],[2,3,4])))

Output:

[4, 27, 256]
[4, 27, 256]

 

 

Summary

The python map() function is a Python built-in function that allows us to iterate over iterable without using explicitly any loop. In this tutorial, we had learned how to python map is used and what characteristics give it more importance than a loop. We also looked at some of the common examples where using map() function can be more helpful. Moreover, we covered some of the alternatives that can be used to replace the python map.

 

Further reading section

Python built-in functions
Python map()
Python map() and other functions

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment