The map() Function in Python

The map() Function in Python

03 Jul 2024
Beginner
1.95K Views
15 min read

The map() Function

The map() function in Pythonis used to apply a function to each element of an iterable such as a list or a tuple and returns a new iterable with the outcomes. Python is a strong programming language that provides different built-in functions to perform operations on data and the map() function is one of them.

In this Python Tutorial, we will explore more about the map() function which will include the Syntax of the map( ) function in Python, and the map( ) function with examples in Python. So let's see first What the map( ) function is in Python.

What is the map() function?

  • The map() function has two arguments, a function and an iterable.
  • The first argument is the function contention and It will be applied to every element of the iterable.
  • The second argument is the iterable contention and It is a sequence or collection of iterable objects which is to be mapped.

map() function

Syntax

Here is the syntax of the map() function in Python

 map(function, iterables)    

Python map() Function Examples

Example 1

Using map() to square a list of numbers
One normal use of the map() function is to apply a numerical activity to every element of a list, here is an example of using the map() function to square a list of numbers, Let's elaborate on this in Python Compiler.

# Python example program for map() function  
numbers = [3, 4, 9, 4, 3]  
# lambda function defines the squaring operation  
squared_numbers = list( map( lambda x : x**2, numbers ))  
  
# print the list of squared numbers  
print(squared_numbers)  
    

Output

 [9, 16, 81, 16, 9]   

Explanation

  • So, In this example, we have a list of numbers and we want to square every one of them.
  • We used the lambda function here to characterize the figuring-out activity, and then we passed that function and the list of numbers to the map() function.
  • The map() function applied the lambda function to every element of the list and returned a new iterable with the squared numbers.

Example 2

Using the map() function to convert temperatures from Celsius to Fahrenheit.
One more use of the map() function is to apply a change trick to every element of an iterable. Here is a program of using the map() function to convert temperatures from Celsius to Fahrenheit, Let's elaborate on this in Python Compiler.
# Python example program for map() function  
temperatures = [0, 5, 15, 20, 25]  
# lambda function defines the conversion formula  
fahrenheit_temperatures = list(map( lambda x : (9/5)*x + 32, temperatures ))  
  
# print the list of Fahrenheit temperatures  
print(fahrenheit_temperatures)  
    

Output

[32.0, 41.0, 59.0, 68.0, 77.0]   

Explanation

  • So, In this example, we have a list of temperatures in Celsius and we want to convert them to Fahrenheit.
  • We used the lambda function to characterize the change recipe, and then we passed that function and the list of temperatures to the map() function.
  • The map() function applied the lambda function to every element of the list and returned a new iterable with the converted temperatures.

Example 3

Using the map() function to concatenate multiple strings
The map() function can likewise be used to apply a string activity to every element of an iterable. Here is an example of using the map() function to concatenate strings:

# Python example program for map() function  
words = ["Welcome","to","Scholarhat"]  
# lambda function defines the string operation  
concatenated_words = list(map(lambda x : x.capitalize( ) + "!", words))  
  
# print the list of concatenated words  
print(concatenated_words)  
    

Output

['Welcome!', 'To!', 'Scholarhat!']   

Explanation

  • So, In this example, we have a list of words and we want to underwrite each word and add an interjection imprint as far as possible.
  • Here, We used the lambda function to characterize the string activity, and then we passed that function and the list of words to the map() function.
  • The map() function applied the lambda function to every element of the list and returned a new iterable with the concatenated strings.

Example 4

Using map () function with tuple

def example(s):

    return s.upper()

tuple_exm = ('Welcome','to','Scholarhat')

upd_tup = map(example, tuple_exm)

print(upd_tup)

print(tuple(upd_tup))
    

Output

<map object at 0x7fd663cb9640>
('WELCOME', 'TO', 'SCHOLARHAT')

Explanation

  • So, In this program, we have taken a tuple with some string values.
  • Then we defined a function to convert the strings to uppercase.
  • And Lastly, we used the map in Python for the tuple and the function, to convert the string values to uppercase.

Using Map in Python with Lambda Functions

The map() function in Python takes in a function and a list as a parameter. This function is called with a lambda function and a list and a new list is returned which contains all the lambda-modified items returned by that function for each thing.

Example:

li = [9, 7, 22, 77, 54, 62, 77, 93, 73, 61]
final_list = list(map(lambda x: x*2, li))
print(final_list)

Output

[18, 14, 44, 154, 108, 124, 154, 186, 146, 122]

Explanation:

Increase all components of a list by 2 utilizing lambda and map() functions.The code copies each component in a list using a lambda function and the 'map' function. It at that point prints the new list with the multiplied components. The output displays each component from the initial list, increased by 2.

Using Map in Python with Dictionary

A dictionary in Python is a collection type that stores keys with value pairs.The dictionary defined using curly brackets. In the example below, we will implement a dictionary of boy names and append the names with a ‘_’ at the end by using the map() function.

Example:

boy_dict ={'a': 'Ankit', 'b': 'vishvaraj', 'c': 'mohan', 'd': 'rocky', 'e': 'Jayesh'}
# adding an '_' to the end of each value
boy_dict = dict(map(lambda x: (x[0], x[1] + '_'), boy_dict.items() ))
print('The modified dictionary is : ')
print(boy_dict)

Output

The modified dictionary is : 
{'a': 'Ankit_', 'b': 'vishvaraj_', 'c': 'mohan_', 'd': 'rocky_', 'e': 'Jayesh_'}

How to Use Map() With Set

Here, we can also use a set with the Python map() function. In the example below, We defined a set with some numbers and printed each value’s remainder when divided by 2.

Example

def example(i):
 return i%2
set_exm = {24, 102, 62, 46, 44, 28, 222}
upd_itms = map(example, set_exm)
print(upd_itms)
print(set(upd_itms))

Output

{0}

String Modification using map()

In this example, we used the map() function to modify the string. Hence We can create a map from an iterable in Python.

Example

# List of strings
l = ['mom', 'tom', 'com', 'rom']
# map() can listify the list of strings individually
test = list(map(list, l))
print(test)

Output

[['m', 'o', 'm'], ['t', 'o', 'm'], ['c', 'o', 'm'], ['r', 'o', 'm']]

if Statement with map()

In the example, the double_even() function doubles even numbers and leaves odd numbers unchanged. The map() function is used to apply this function to each element of the numbers list, and an if statement is used within the function to perform the necessary conditional logic.

Example

# Define a function that doubles even numbers and leaves odd numbers as is
def double_even(num):
	if num % 2 == 0:
		return num * 2
	else:
		return num
# Create a list of numbers to apply the function to
numbers = [4, 5, 6, 7, 8]

# Use map to apply the function to each element in the list
result = list(map(double_even, numbers))
# Print the result
print(result)

Output

[8, 5, 12, 7, 16]
Conclusion
In Conclusion, The map() function is an incredible method in Python that can be used to apply a function to each element of an iterable and return a new iterable with the outcomes. It is a flexible function that can be used with numerical operations, transformation recipes, and string operations. However, to simplify development and up your game, learn the intricacies of Python with Scholarhat and level up as a Python developer.

FAQs

It creates a new array by calling a function for every array element.

The are other functions like map() such as filter(), and reduce() 

The map() function returns a new array containing the square roots.
Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this