Simple way to understand map() function in Python

Simple way to understand map() function in Python

1 min read

The map() function is used to apply a particular function to every element of a list. Its syntax is very simple to use.

map(function, sequence)

After applying the specified function or defined function on the sequence, the map() function returns the modified list. The map() function calls function(item) for each item in the sequence and return a list of the return values.

def multiply(x):
    return x*2
freshlybuilt_list = [1,2,3,4,5,6]
freshlybuilt_list = list(map(multiply,freshlybuilt_list))
print(" New Updated List is : ", freshlybuilt_list )


New Updated List is : [2, 4, 6 ,8, 10, 12]

In the above code, the map() function call multiply() which multiply 2 to every value in the list. Interesting is to note that, You can even pass more than one sequence in the map() function. But in this case, remember two things.

  • First, the function must have as many arguments as there are sequences.
  • Second, each argument is called with the corresponding item from each sequence( or None if one sequence is shorter than another).
def multiply(x,y):
    return x*y
x_list = [9, 3, 7 , 4]
y_list = [3, 5, 7, 8]
new_list = list(map(multiply, x_list, y_list))
print("Multiply of ", x_list, " and ", y_list, " = ", new_list)


Multiply of [9, 3, 7, 4] and [3, 5, 7, 8] = [27, 15, 49, 32]

One More example to explain map function further more:

Program to convert strings of all uppercase characters into strings of all lowercase characters using the map() function.

def to_lower(str):
    return str.lower()
s = "Welcome To Freshlybuilt"
fresh_list = s.split() # convert string into list
fresh_list = list(map(to_lower,fresh_list)) #convert elements into lowercase
fresh_list = ' '.join(map(str, fresh_list)) # convert list into string
print(" String in lower case: ", fresh_list)
Choose your Reaction!
Leave a Comment