Python Map() | How to use the map() function with different types of sequences

Python Map() | How to use the map() function with different types of sequences

Python map() function applies another function on a given iterable (List/String/Dictionary, etc.) and returns 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 or 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 Explained

Python Map() Function

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 map object with 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.

Its syntax is as follows:

# Python map() syntax
map(in_function, iterable1[, iterable2, iterable3, ...])

Map() Function Examples

We’ll now give several examples using map() so that 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 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))

Python Function

String As Iterable In Map() Function

The below code pass 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

Python String

List As Iterable In Map() Function

The below code shows how to use a list with the map() function.

"""
 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

Python List

Tuple As Iterable In Map() Function

In this example, we are using a tuple to pass in the 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

Python Tuple

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

Python Set

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 result as:


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.

Python Dictionary

Convert Map Object To A Sequence

We’ve said earlier that you could use constructor functions to convert a map to 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'.

Map() Function With Multiple Iterables

In this example, we’ll demonstrate how to pass multiple iterables to 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 in using the Python map() function. However, you may practice more with examples to gain confidence.

python

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Python Programming: A Beginner’s Guide

Python is an interpreted, high-level, powerful general-purpose programming language. You may ask, Python’s a snake right? and Why is this programming language named after it?

Hire Python Developers

Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, our full-stack Python development services...

Python any: How to Check If Element is Iterable or Not

Python any() function returns True if any element of an iterable is True otherwise any() function returns False. The syntax is any().