20
DecThe map() Function in Python
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.
Syntax
Here is the syntax of the map() function in Python
map(function, iterables)
Python map() Function Examples
Example 1
# 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
# 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
# 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
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
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()
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]