Python map() function applies another function on a given iterable (List/String/Dictionary, etc.) and returns a map object. In simple words, it traverses the list, calls the function for each element, and returns the results.
Python map object is also iterable holding the list of each iteration. We can also convert it to List, Dictionary, or other types using their constructor functions.
In this tutorial, you’ll learn how to use the map() function with different types of sequences. Also, you can refer to the examples that we’ve added to bring clarity.
Python map() function with multiple arguments
The map() function takes at least two parameters. The first argument is a user-defined function, and then one or more iterable types.
If you pass only one iterable, then map() calls the function for each of its elements and returns the map object with the results.
However, if you provide multiple iterables, then the function will be called with each of their elements as arguments. In this case, the map() call stops after finishing up the shortest iterable argument.
The syntax of the Python map() function is as follows:
# Python map() syntax map(in_function, iterable1[, iterable2, iterable3, ...])
Using map() function with examples
We’ll now give several Python code examples using map() in Python. You can clearly understand: “What does it do and how should you use it”.
But before beginning, we need a user-defined function that we can pass as the first argument to map(). So, here it is:
# User-defined function to pass to map() # function as the first argument def getLength(iterable): return len(iterable)
It calculates the length of the iterable and returns in a map object. Below is a method to print the map object. We’ll use it in all our examples.
# Function to print the map output def show_result(map_object): for item in map_object: print(item, end=' ') print('') # for new line
Also, we’ll use one more generic function to print the iterable.
# Generic Function to print the iterator and its content def print_Iter(iter_in): if isinstance(iter_in, str): print("The input iterable, '{}' is a String. Its length is {}.".format(iter_in, len(iter_in))) if isinstance(iter_in, (list, tuple, set)): print("The input iterable, {} is a {}. It has {} elements.".format(iter_in, type(iter_in).__name__, len(iter_in))) for item in iter_in: print("The {} contains '{}' and its length is {}.".format(type(iter_in).__name__, item, len(item))) if isinstance(iter_in, dict): print("The input iterable, {} is a {}. It has {} elements.".format(iter_in, type(iter_in).__name__, len(iter_in))) for key, value in iter_in.items(): print("Dict key is '{}' and value is {}.".format(key, value))
In the above example, we created a print_Iter
which is a user-defined function. To know more, read how to write and call a function in Python.
Using a string with map() function in Python
The below code passes a String type iterable in the map() and prints the result.
""" Desc: Python map() function to apply on a String iterable """ # Considering String as our iterable parameter iter_String = "Python" print_Iter(iter_String) # Calling map() function on a string map_result = map(getLength, iter_String) print("Type of map_result is {}".format(type(map_result))) # Printing map() output print("Lengths are: ") show_result(map_result)
Please note that you’ll need to add the definition of the print_Iter(), getLength(), and show_result() in the above example. After that, you can run it. The output is:
The input iterable, 'Python' is a String. Its length is 6. Type of map_result is <class 'map'> Lengths are: 1 1 1 1 1 1
Strings are the most common Python data types. It is even hard to think about a Python program without using a string. Hence, it is essential that you should read our guide to Python strings.
Passing a list in the map() function
The below code shows how to use a list with the map() function in Python.
""" Desc: Python map() function to apply on a List iterable """ # Considering List as our iterable parameter iter_List = ["Python", "CSharp", "Java"] print_Iter(iter_List) # Calling map() function on a list map_result = map(getLength, iter_List) print("Type of map_result is {}".format(type(map_result))) # Printing map() output print("Lengths are: ") show_result(map_result)
The output is as follows:
The input iterable, ['Python', 'CSharp', 'Java'] is a list. It has 3 elements. The list contains 'Python' and its length is 6. The list contains 'CSharp' and its length is 6. The list contains 'Java' and its length is 4. Type of map_result is <class 'map'> Lengths are: 6 6 4
Similar to strings, lists too are often used in Python programs. They can store different types of information and also provides the ability to fetch and update data as needed. If you seek more info, explore our detailed guide on lists in Python.
Tuple as iterable in map() function
In this example, we are using a tuple to pass in the Python map() function.
""" Desc: Python map() function to apply on a Tuple iterable """ # Considering Tuple as our iterable parameter iter_Tuple = ("Python", "CSharp", "Java") print_Iter(iter_Tuple) # Calling map() function on a tuple map_result = map(getLength, iter_Tuple) print("Type of map_result is {}".format(type(map_result))) # Printing map() output print("Lengths are: ") show_result(map_result)
Running the above code brings the following output:
The input iterable, ('Python', 'CSharp', 'Java') is a tuple. It has 3 elements. The tuple contains 'Python' and its length is 6. The tuple contains 'CSharp' and its length is 6. The tuple contains 'Java' and its length is 4. Type of map_result is <class 'map'> Lengths are: 6 6 4
Tuples are similar to lists, but they are immutable, which means that they cannot be changed once they are created. Consider checking out when and how to use tuples in Python.
Set as iterable in map() function
Here, we are using a set type object to pass in the map() function and will see how it works.
""" Desc: Python map() function to apply on a Set iterable """ # Considering Set as our iterable parameter iter_Set = {"Python", "CSharp", "Java"} print_Iter(iter_Set) # Calling map() function on a set map_result = map(getLength, iter_Set) print("Type of map_result is {}".format(type(map_result))) # Printing map() output print("Lengths are: ") show_result(map_result)
The result:
The input iterable, {'CSharp', 'Python', 'Java'} is a set. It has 3 elements. The set contains 'CSharp' and its length is 6. The set contains 'Python' and its length is 6. The set contains 'Java' and its length is 4. Type of map_result is <class 'map'> Lengths are: 6 6 4
Unlike a list, sets contain only unique elements, they are unordered and unchangeable. You can try understanding Python set with examples from our blog.
Dictionary as iterable in map() function
Finally, we’ll apply the map() function to a dictionary type and see how it goes.
""" Desc: Python map() function to apply on a Dict iterable """ # Considering Dict as our iterable parameter iter_Dict = {"Python":0, "CSharp":0, "Java":0} print_Iter(iter_Dict) # Calling map() function on a dictionary map_result = map(getLength, iter_Dict) print("Type of map_result is {}".format(type(map_result))) # Printing map() output print("Lengths are: ") show_result(map_result)
When you run the above example, it produces the following result:
The input iterable, {'Java': 0, 'CSharp': 0, 'Python': 0} is a dict. It has 3 elements. Dict key is 'Java' and value is 0. Dict key is 'CSharp' and value is 0. Dict key is 'Python' and value is 0. Type of map_result is <class 'map'> Lengths are: 4 6 6
The program prints the length of dictionary keys. From here, learn more about dictionaries in Python.
Convert map object to a sequence
We’ve said earlier that you could use constructor functions to convert a map to a list, tuple, set, etc. So, see this happening below.
""" Desc: Program to convert map object to list, tuple, and set """ # User-defined function to pass to map() # function as the first argument def getLength(iterable): return len(iterable) # Function to print the map output def show_result(iter_in): print("****************************") print("The input iterable, {} is a {}.".format(iter_in, type(iter_in).__name__)) for item in iter_in: print("The {} contains '{}'.".format(type(iter_in).__name__, item)) # Converting map object to a list map_result = map(getLength, ["Python", "JavaScript", "Java"]) to_list = list(map_result) show_result(to_list) # Converting map object to a tuple map_result = map(getLength, ["Python", "JavaScript", "Java"]) to_tuple = tuple(map_result) show_result(to_tuple) # Converting map object to a set map_result = map(getLength, ["Python", "JavaScript", "Java"]) to_set = set(map_result) show_result(to_set)
The above example produces the following result:
**************************** The input iterable, [6, 10, 4] is a list. The list contains '6'. The list contains '10'. The list contains '4'. **************************** The input iterable, (6, 10, 4) is a tuple. The tuple contains '6'. The tuple contains '10'. The tuple contains '4'. **************************** The input iterable, {10, 4, 6} is a set. The set contains '10'. The set contains '4'. The set contains '6'.
Python map() with the anonymous function
You’ve read our Python lambda tutorial which is also known as Anonymous function. In the map() call, we can send it as the first parameter.
This function is inline, and we can easily implement the length functionality using it. See the below example.
""" Desc: Python program to use lambda with map() function """ # Function to print the map output def show_result(iter_in): print("****************************") print("The input iterable, {} is a {}.".format(iter_in, type(iter_in).__name__)) for item in iter_in: print("The {} contains '{}'.".format(type(iter_in).__name__, item)) # Using lambda function with map() map_result = map(lambda item: len(item), ["Python", "JavaScript", "Java"]) to_list = list(map_result) show_result(to_list)
The output is as follows:
**************************** The input iterable, [6, 10, 4] is a list. The list contains '6'. The list contains '10'. The list contains '4'.
Similar to map(), Python zip() is another versatile function available for our disposal. It is used to combine, compare, and iterate lists in parallel.
map() function with multiple iterables
In this example, we’ll demonstrate how to pass multiple iterables to the map() function. Check the sample code below.
""" Desc: Python program to use lambda with map() function """ # Function to print the map output def show_result(iter_in): print("****************************") print("The input iterable, {} is a {}.".format(iter_in, type(iter_in).__name__)) for item in iter_in: print("The {} contains '{}'.".format(type(iter_in).__name__, item)) # Using lambda function with map() map_result = map(lambda arg1, arg2, arg3: [len(arg1), len(arg2), len(arg3)], ["Python", "JavaScript", "Java"], ("Go", "C", "C++", "Pascal"), {"Delphi", "VC++", "PHP", "MySQL", "MariaDB"}) to_list = list(map_result) show_result(to_list)
The output:
**************************** The input iterable, [[6, 2, 6], [10, 1, 7], [4, 3, 4]] is a list. The list contains '[6, 2, 6]'. The list contains '[10, 1, 7]'. The list contains '[4, 3, 4]'.
You can see the lambda function is taking three arguments as we are using three iterables. Also, the shortest of them is having three elements. Hence, it gets called three times.
We hope that after wrapping up this tutorial, you should feel comfortable using the Python map() function. However, you may practice more with examples to gain confidence.
Also, to learn Python from scratch to depth, do read our step-by-step Python tutorial.