Tutorial

Python map() function

Published on August 3, 2022
author

Pankaj

Python map() function

Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc. using their factory functions.

Python map() function

Python map() function syntax is:

map(function, iterable, ...)

We can pass multiple iterable arguments to map() function, in that case, the specified function must have that many arguments. The function will be applied to these iterable elements in parallel. With multiple iterable arguments, the map iterator stops when the shortest iterable is exhausted.

Python map() example

Let’s write a function to be used with map() function.

def to_upper_case(s):
    return str(s).upper()

It’s a simple function that returns the upper case string representation of the input object. I am also defining a utility function to print iterator elements. The function will print iterator elements with white space and will be reused in all the code snippets.

def print_iterator(it):
    for x in it:
        print(x, end=' ')
    print('')  # for new line

Let’s look at map() function example with different types of iterables.

Python map() with string

# map() with string
map_iterator = map(to_upper_case, 'abc')
print(type(map_iterator))
print_iterator(map_iterator)

Output:

<class 'map'>
A B C 

Python map() with tuple

# map() with tuple
map_iterator = map(to_upper_case, (1, 'a', 'abc'))
print_iterator(map_iterator)

Output:

1 A ABC 

Python map() with list

map_iterator = map(to_upper_case, ['x', 'a', 'abc'])
print_iterator(map_iterator)

Output:

X A ABC 

Converting map to list, tuple, set

Since map object is an iterator, we can pass it as an argument to the factory methods for creating a list, tuple, set etc.

map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_list = list(map_iterator)
print(my_list)

map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_set = set(map_iterator)
print(my_set)

map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_tuple = tuple(map_iterator)
print(my_tuple)

Output:

['A', 'B', 'C']
{'C', 'B', 'A'}
('A', 'B', 'C')

Python map() with lambda

We can use lambda functions with map() if we don’t want to reuse it. This is useful when our function is small and we don’t want to define a new function.

list_numbers = [1, 2, 3, 4]

map_iterator = map(lambda x: x * 2, list_numbers)
print_iterator(map_iterator)

Output:

2 4 6 8 

Python map() multiple arguments

Let’s look at an example of using map() function with multiple iterable arguments.

# map() with multiple iterable arguments
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8)
map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers)
print_iterator(map_iterator)

Output: 5 12 21 32 Notice that our function has two arguments. The output map iterator is the result of applying this function to the two iterable elements in parallel. Let’s see what happens when the iterables are of different sizes.

# map() with multiple iterable arguments of different sizes
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8, 9, 10)
map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers)
print_iterator(map_iterator)

map_iterator = map(lambda x, y: x * y, tuple_numbers, list_numbers)
print_iterator(map_iterator)

Output:

5 12 21 32 
5 12 21 32 

So when the arguments are of different sizes, then the map function is applied to the elements until one of them is exhausted.

Python map() with function None

Let’s see what happens when we pass the function as None.

map_iterator = map(None, 'abc')
print(map_iterator)
for x in map_iterator:
    print(x)

Output:

Traceback (most recent call last):
  File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_map_example.py", line 3, in <module>
    for x in map_iterator:
TypeError: 'NoneType' object is not callable

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 24, 2020

Hi Pankaj - thank you for the explanation, this is most helpful - I read somewhere that the map object is a view object - is that the case?

- RS

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 7, 2020

    Thank you so much for this useful information. I didnt know i needed it for my data science lectures. Thank you

    - Phil

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 4, 2019

      thanks for the input!

      - bluegarden

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 17, 2018

        HI Pankaj, very good work man. Very helpful article. However, for the code “# map() with multiple iterable arguments of different sizes” the output is missing.

        - Deepak Shukla

          Try DigitalOcean for free

          Click below to sign up and get $200 of credit to try our products over 60 days!

          Sign up

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Become a contributor for community

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          DigitalOcean Documentation

          Full documentation for every DigitalOcean product.

          Resources for startups and SMBs

          The Wave has everything you need to know about building a business, from raising funding to marketing your product.

          Get our newsletter

          Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

          New accounts only. By submitting your email you agree to our Privacy Policy

          The developer cloud

          Scale up as you grow — whether you're running one virtual machine or ten thousand.

          Get started for free

          Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

          *This promotional offer applies to new accounts only.