This blog aims to clarify the Python map function, a handy feature in programming. We’ll examine its operation with different built-in functions, offering code snippets to illustrate its workings.
Table of Contents
Watch this Python Tutorial Video for Beginners:
Introduction to the Python map() Function
Often, when you’re dealing with a list of items in Python, there’s a common need to perform a specific action or task on each item and create a new set of results. This is where the Python ‘map()’ function comes into play. It lets you apply a particular operation or function to every element in a list without having to write a traditional ‘for’ loop. This process is called mapping.
In simpler terms, if you want to transform each item in a list using a specific function and generate a new set of results, the ‘map()’ function is the go-to tool for the job. It streamlines the process and makes your code cleaner and more efficient.
How Does the map() Function Work?
In Python, a map function is a versatile tool that takes a function and one or more iterables as input. It then systematically applies the specified function to each item in the iterable, storing the results in a map object.
Let’s see a practical example to understand the concept better. Consider the task of multiplying each number in a list by itself. Initially, you can achieve this using a traditional for loop, as shown in the example below:
num = [4, 5, 6, 10, 13]
mul = []
for n in num:
mul.append(n ** 2)
print(mul)
Output:
[16, 25, 36, 100, 169]
Alternatively, we can achieve the same result using the Python `map()` function. Let’s see how:
def mul(i):
return i * i
num = (3, 5, 7, 11, 13)
resu = map(mul, num)
# Making the map object readable
mul_output = list(resu)
print(mul_output)
Output:
[9, 25, 49, 121, 169]
Here, the `map()` function operates similarly to a for loop by iterating through the iterable and applying the specified function. Once the iteration is complete, it returns a map object. To obtain a readable output, you can convert this map object to a list, as demonstrated.
One key observation is that when using the map in Python, you have the flexibility to define the iterable separately and then pass it to the `map()` function. Alternatively, you can define the iterable within the `map()` function itself. This showcases the adaptability and convenience offered by the `map()` function in various scenarios.
Syntax of the map() Function
Here is the syntax of the map function in Python:
map(function, iterable, ...)
Explanation:
The ‘map()’ function is used to apply a specified function to every element in an iterable object (like lists, tuples, dictionaries, sets, etc.).
- ‘function’: This is the transformation function that ‘map()’ applies to each element in the iterable.
- ‘iterable’: It refers to the data structure (e.g., lists, tuples, etc.) containing the elements on which the function will be applied.
Note: You can pass multiple iterables to the ‘map()’ function.
Return Type of map() Function
The ‘map()’ method gives us a list of results. The output from ‘map()’ can be used with other methods like ‘list()’ (to create a list), ‘set()’ (to make a set), or ‘tuple’, depending on your needs. This flexibility allows you to easily work with the transformed data in various formats.
Enroll in Python Online Training to become a Python expert!
Get 100% Hike!
Master Most in Demand Skills Now!
Using map() with Python’s Built-in Functions
Let’s explore the versatility of Python’s map() function by combining it with other built-in functions. In this example, we’ll leverage the round() built-in function to round the values within a given list.
Consider the following list:
old_list = [1.5643, 3.73426, 4.23245, 5.77967, 6.92465, 7.8988, 8.23462, 9.34907]
Our goal is to obtain rounded values for each item in the list. To achieve this, we will apply the round() function using the map() function.
old_list = [1.5643, 3.73426, 4.23245, 5.77967, 6.92465, 7.8988, 8.23462, 9.34907]
new_list = map(round, old_list)
print(list(new_list))
Output:
[2, 4, 4, 6, 7, 8, 8, 9]
The round() function is seamlessly applied to all items in the list, resulting in a new list where each value is rounded. The output displays the modified list, providing a clear illustration of the map() function’s effectiveness in combination with built-in functions.
Using map() with List of Numbers
Let’s explore how to use the map() function to multiply each number in a list by 10, making the process simpler and more readable.
We have a list of numbers:
numbers_list = [4, 5, 6, 7, 8, 9]
Our goal is to multiply each number in this list by 10. To achieve this, we’ll define a function called multiply_by_10().
def multiply_by_10(number):
return number * 10
numbers_list = [4, 5, 6, 7, 8, 9]
result = map(multiply_by_10, numbers_list)
result_list = list(result)
print(result_list)
In this example, the ‘multiply_by_10()’ function takes a number as input and returns the result of multiplying it by 10. We then use the ‘map()’ function, in which we will be passing our function and the list of numbers. The result is a new iterable, which we convert to a list for better readability.
The output of our code is:
[40, 50, 60, 70, 80, 90]
This means that each number in the original list has been multiplied by 10, providing us with the updated list. The use of the map() function simplifies the process and enhances the readability of our code.
Using map() with a String as an Iterator
In Python, you can use ‘map()’ not only with lists but also with strings. A string in Python can be treated like an array, making it easy to work with ‘map()’.
Let’s take a look at an example:
# Define a function to convert a string to uppercase
def convert_to_uppercase(char):
return char.upper()
# The input string
my_str = "welcome to intellipaat!"
# Apply the function using map() to convert each character to uppercase
updated_list = map(convert_to_uppercase, my_str)
# Display the result
for char in updated_list:
print(char, end="")
Output:
WELCOME TO INTELLIPAAT!
In this example, the ‘convert_to_uppercase()’ function is applied to each character in the input string using ‘map()’. The result is a new string with all characters converted to uppercase.
Using map() with Tuple
In Python, a tuple is a collection of items separated by commas and enclosed in round brackets. Let’s consider an example where we have a tuple containing string values. Our goal is to convert these values to uppercase using a specific function.
Here’s the code to implement it:
def convert_to_uppercase(value):
return value.upper()
my_tuple = (‘python’, ’php’, ‘c++’, ‘c’, ‘java’)
updated_list = map(convert_to_uppercase, my_tuple)
# The following two lines are for displaying the result
print("Result as a map object:", updated_list)
print("Result as a list:", list(updated_list))
In this code, the `convert_to_uppercase` function takes a value and uses the `upper()` method to convert it to uppercase. We then have a tuple named `my_tuple` with some string values. The `map` function applies the `convert_to_uppercase` function to each element in the tuple.
Now, if you run this code, you might be surprised by the output. The first print statement shows ‘<map object at 0x7fee6564b970>’, which might not make much sense at first. But don’t worry, we can make it clearer.
The second output of this code is a list with all the values converted to uppercase:
Result as a map object: <map object at 0x7fee6564b970>
Result as a list: [‘PYTHON’, ‘PHP’, ‘C++’, ‘C’, ‘JAVA’]
The list displayed contains the uppercase versions of the string values in the original tuple.
Looking to Data Science with Python All-in-1 Combo Training? Enroll now!
Using map() with Lambda function
In Python, lambda expressions allow you to create anonymous functions. They’re like short, on-the-fly functions that you can use without formally defining them using the “def” keyword.
Let’s take an example: Suppose you have a list of numbers, and you want to multiply each number by 10. You can achieve this using the ‘map()’ function along with a lambda expression.
Here’s the example:
original_list = [4, 5, 6, 7, 8, 9]
# Using lambda function inside map() to multiply each value by 10
updated_list = map(lambda num: num * 10, original_list)
# Displaying the result
print("Updated List:")
print(list(updated_list))
In this code, ‘original_list’ contains the initial numbers. The lambda function inside the ‘map()’ function multiplies each number by 10. Finally, we print the updated list to see the result.
When you run this code, you’ll get the following output:
Updated List:
[40, 50, 60, 70, 80, 90]
This result shows the list with each element multiplied by 10. The lambda expression provides a concise way to express the transformation you want to apply to each element in the list.
Using map() with Dictionary
In Python, a dictionary is created using curly brackets ‘{}’. Since a dictionary is iterable, it can be used inside the ‘map()’ function. Let’s see how we can use a dictionary as an iterable inside the ‘map()’ function.
Consider the following example:
def multiply_by_10(value):
return value * 10
my_dict = {4, 5, 6, 7, 8, 9}
result = map(multiply_by_10, my_dict)
print(result)
print(list(result))
Output:
<map object at 0x7feb16a37a30>
[40, 50, 60, 70, 80, 90]
In this example, we define a simple function ‘multiply_by_10’ that multiplies its input by 10. The ‘map()’ function applies this function to each element of the dictionary ‘my_dict’. The result is then printed as a map object and as a list, showing the elements multiplied by 10.
Using map() with Set
A set in Python is a unique collection of items enclosed in curly brackets. Think of it like a bag where each item is distinct and the order doesn’t matter.
Now, sets can be pretty handy. They are not just a bunch of items; they can also be used in cool functions like map(). In Python, a set is also considered an iterator, and that makes it interesting.
Let’s go through a practical example. We have this function called myMapFunc(n), and all it does is multiply the input by 10. Then, we have a set named my_set containing some numbers.
def myMapFunc(n):
return n * 20
my_set = {4, 5, 6, 7, 8, 9}
final_items = map(myMapFunc, my_set)
print(final_items)
print(list(final_items))
Output:
<map object at 0x7fa8cfe7c310>
[80, 100, 120, 140, 160, 180]
So, what’s happening here is that we applied the myMapFunc() function to each item in the set using the map() function. The set, being an iterator, makes this process quite elegant.
Give it a try with your own set of numbers and functions! It’s a neat way to process data in Python.
Intellipaat is providing free Python Interview Questions and Answers, which will help you excel in your career!
Using Multiple Iterators Inside map() Function
Let’s explore how you can leverage the map() function to work with multiple iterators simultaneously.
Example 1: Combining Two Lists
You have the flexibility to send more than one iterator, such as lists or tuples, to the map() function. Consider a scenario where you want to add corresponding elements from two lists, my_list1 and my_list2. The map() function allows you to achieve this seamlessly.
def add_lists(item1, item2):
return item1 + item2
my_list1 = [6, 7, 8, 9]
my_list2 = [16, 20, 24, 28]
resultant_list = map(add_lists, my_list1, my_list2)
print(resultant_list)
print(list(resultant_list))
Output:
<map object at 0x7f647fb50220>
[22, 27, 32, 37]
Example 2: Combining List and Tuple
You can also use a combination of a list and a tuple iterator within the map() function. In the following example, the myMapFunc() function concatenates items from the list and the tuple, joining them with an underscore (_).
def combine_items(item1, item2):
return item1 + "_" + item2
my_list = ['a', 'b', 'c']
my_tuple = ('Intellipaat', 'Great Learning', 'Analytics Vidhya')
combined_list = map(combine_items, my_list, my_tuple)
print(combined_list)
print(list(combined_list))
Output:
<map object at 0x00000059F37BB4E0>
[‘a_Intellipaat’, ‘b_Great Learning’, ‘b_Analytics Vidhya’]
In both examples, the map() function efficiently applies the specified function to corresponding elements from the given iterators, offering a concise and readable way to handle multiple iterators simultaneously.
Conclusion
The Python ‘map()’ function is a handy tool that makes working with lists, tuples, and other stuff in Python easier. It lets you do things to every item in a list without using those confusing loops. You can use it with different functions, like built-in ones or ones you make up on the spot. It’s pretty cool because it helps your code look cleaner and does the job quicker. So, when you want to deal with lots of things in Python, ‘map()’ is your friend!