Python map() function

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

The map() built-in function returns an iterator after applying the function to each item in the sequence. Its syntax is as follows:

Syntax: map(function, sequence[, sequence, ...]) -> map object

Python 3

Here the items in the list are passed to the ord()  built-in function one at a time.

Since map()  returns an iterator, we have used the list()  function to produce the result at once.

The preceding code is functionally equivalent to the following:

Python 3

However, using map()  results in shorter code and is often run faster.

In Python 2, the map()  function returns a list instead of an iterator (which is not very efficient in terms of memory consumption), so we don’t need to wrap map()  in a list()  call.

Python 2

Passing User-defined Function

In the following listing, we are passing a user-defined function to the map()  function.

Python 3

Here, the function multiplies each item in the list by 2.

Passing Multiple Arguments

If we pass n  sequences to map(), the function must take n  number of arguments and items from the sequences are consumed in parallel, until the shortest sequence is exhausted. In Python 2, however, the map()  function stops when the longest sequence is exhausted and value of None is used as padding when the shorter sequence is exhausted.

Python 3

Python 2

Passing Lambda

If your function doesn’t mean to be reused you can pass a lambda (inline anonymous function) instead of a function.

Python 3

Here, the function multiples each item in the list by 5.

Pairing Items (Only in Python 2)

Finally, you can pair items from multiple sequences by passing None in place of a function:

Python 2

Notice that when the shorter sequence is exhausted None is used to pad the result.

This form of map() not valid in Python 3.

If you want to pair items from multiple sequences use the zip() function.

Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Leave a Reply

Your email address will not be published. Required fields are marked *