In this tutorial, you’ll learn how to use the Python map() function with different types of sequences. Also, you can refer to the examples that we’ve added to bring clarity.
The purpose of the Python map
function is to apply a given function to each element in an iterable. It is useful when you want to transform or process data in a collection, such as a list, by applying the same operation to each element.
This is particularly useful for tasks like data manipulation, calculation, or any scenario where you want to avoid writing repetitive loop structures, making your code more concise and readable. Essentially, map
helps you efficiently apply a function to multiple items in a collection, promoting cleaner and more expressive code.
How to call 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, ...])
Parameters | Short Description |
---|---|
in_function | It is the function you want to apply to each item in the iterable. It can be a built-in function, a lambda function, or a custom function you define. |
iterable1[, iterable2, iterable3, ...] | The second argument is the iterable (e.g., list, tuple) that contains the elements you want to process with the given function. |
Return Value:
The map()
function returns a map object, which is an iterator. It holds the results of applying the specified function to each element in the iterable, one by one. To get the results in a more conventional format (e.g., a list), you can convert the map object to a list using list(map(function, iterable))
.
Errors and Exceptions:
The map() function can fail with the following:
- TypeError: The map call fails if the function provided is not callable.
- TypeError: Assume, you pass a list to map but it is not actually a list, it will fail.
- StopIteration: When you attempt to access elements beyond what’s available in the map object (by looping through it, for example), it causes the StopIteration error.
To understand about these, you may refer to try-except in Python describing the topic in depth.
Examples of using Python map() function
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 are often used in Python programs. They can store different types of information and also provide 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 sets 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)
When you run the above example, it prints 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'.
Using Python map() with the lambda 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 write a program to find the length of a list 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 cool function available for use. It merges, compares, and loops through lists in parallel.
Using the map() function with multiple lists
In this example, we’ll show how to pass multiple lists 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 lists. Also, the shortest of them has three elements. Hence, it gets called three times.
Conclusion – Learning Python map()
We hope that after wrapping up this tutorial, you will feel comfortable using the Python map() function. However, you may practice more with examples to gain confidence.
Python map is a powerful function that allows you to apply a function to each item in an iterable and return a new object. It is a clean way to carry out common tasks such as changing data, filtering, and merging.
To learn Python map:
- Understand iterables (objects that you can run over, such as lists, tuples, or strings).
- Pass in the function and iterable to the map function.
- The map function will apply the function to each item in the iterable and return a new one.
The map function:
- Applies the function to each item in the iterable.
- Returns a new iterable.
Python map is versatile:
- Can be used to perform a variety of tasks.
- Makes code more concise and efficient.
Examples:
- Convert a list of strings to lowercase:
map(str.lower, ["HELLO", "WORLD"])
. - Calculate the square root of each item in a list:
map(math.sqrt, [1, 4, 9, 16])
. - Filter out even numbers from a list:
map(lambda x: x if x % 2 != 0 else None, [1, 2, 3, 4, 5])
. - Merge two lists into a single list:
map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6])
.
Learn Python map to write better code.
Also, to learn Python from scratch to depth, read our step-by-step Python tutorial.