Python map function (Applies function to each item in sequence)

Map function is used to apply a function to each of the items in an iterable.

This is particularly useful when you have one of the sequence objects of Python such as dictionaries, tuples, strings, lists, range object etc.

We also have filter() function which is like a sister function to map()

By combining the two, you can first filter the items in a sequence (say a Python list) and then apply map to only those that pass the filter.

You can also do it the other way, map a function to each item in a list and then do it inside a filter function so that only results that pass the filter will be shown.

Estimated Time

10 mins

Skill Level

Intermediate

Functions

map ()

Course Provider

Provided by HolyPython.com

Used Where?

  1. map() function is used to apply a function to each of their elements.
    When you have an iterable data (a list, tuple, string, dictionary etc.),
  2. filter() function, map() function can be used together and they both become more useful. This gives map more control on which values to apply the function to.
  3. This combination makes both functions more powerful. However, in Python, list comprehension and dict comprehension can sometimes make map and filter functions obselete.

Note: Nevertheless, it’s good to know them all (list comprehension, dict comprehension, map, filter, zip etc.) and practice different ways, especially in the beginning of a journey of programming language learning.

map() function examples we’ve prepared for you below can make these concepts more clear in a demonstrative way.

Syntax do(s)

1) inside map function's parenthesis type your function followed by a comma

2) then the name of a list, tuple, dictionary or string

i.e.: map(f, iterable)

Syntax don't(s)

1) Don't print map function directly, you will only get a unique memory address

2) Don't forget to put your map function inside a list() function if you'd like to create meaningful results that are readable by the user.

Example 1: map()

  • You can pass any function that makes sense to your map() function, it doesn’t have to be in the form of . Here is an example where function is defined conventionally and then passed in map() function as an argument.

>>> def add_two(a):
>>>     return a+2

>>> lst = [10, 20, 30]
>>> lst2 = map(add_two, lst)
>>> print(list(lst2))

[12, 22, 32]

Example 2: print with lambda

>>> a = lambda x: print(x*3)
>>> print(a(33))

99

To simplify things let’s explain again for the fresh programmers:

Program starts with lambda, then variable name and colon(:), on the right side of the colon simply statement is made regarding what happens to the and/or with the variable.

Example 3: lambda with logical expression

>>> a = lambda x: x%5==0
>>> print(a(555))
>>> print(a(222))

True
False

Printing the function object

You might at some point encounter a strange output when you’re learning Python. This happens when you try to print function objects directly without without calling it with any value.

What you get will be the id of your function as a memory address rather than any meaningful value to the user.

Example 4: printing the function

>>> a = lambda x: print(“Hi”)
>>> print(a)

at 0x00000163154BB1E0>

But what is the last printed line that looks weird?

This is because we are trying to print the function itself directly without calling it for any values. What happens is, Python prints the unique memory address of our function. That’s why it looks slightly weird. But later it grows on you 🙂

Example 5:

>>> a = lambda x: print(“Hi”)
>>> a()

at 0x00000163154BB1E0>

Another point is that you actually don’t have to call your function inside a print() function when your function already has print in it.

Just call your function and it will do the printing for you.

Example 6:

You can also pass two arguments to your lambda:

>>> a = lambda x, y: x*y
>>> a(11, 6)

66

Tips (optional)

1- One of the most useful aspect of lambda is the ability to pass it as an argument inside some other functions.

We will look at each of these functions in detail in next lessons individually so you don’t have to ponder too much.

But it might be beneficial to take a look at them here to get familiar in advance.

 

Example 7:

.sort() is a list method that sorts the list’s elements directly.

>>> lst = [1, 5, 66, 7]
>>> lst.sort(key=lambda x: x)
print(lst)

[1, 5, 7, 66]

if you’d like to use a function as an argument in .sort() you need to use it with “key=” keyword.

Advanced Concepts (Optional)

1- map() and filter() can complete each other.

If you’d like to filter the elements of your list based on a logical expression, but also map those values to a specific function, you get map() inside filter().

This operation will give same results as filter()inside map(). We also have that second version of this example at the end of filter() function’s lesson here.

  • map() function will produce your filtered iterable inside filter() function as below:
  • filter(function, iterable)
    • where function will be the filtering function
    • where iterable will be: map(function, iterable)
      • where function will be the mapping function
      • and iterable will be the actual iterable list or other.

Let’s see an example.

Example 11: filter with map

  • Inside filter() function, first part tells the filtering criteria (logical expression function), second part is the iterable which is mapped with map function.

>>> lst = [1, 4, 9, 11, 400]
>>> a = filter(lambda x: x<10, lst, map(lambda x: x**2, ))
>>> print(list(a))

[1, 16, 81]

  • ** operator means square of a number in Python. If you’d like to refresh your arithmetic operators knowledge in Python you check a full list here.

  • When you’re using a filter, map or zip function as an iterable in a loop or another function you don’t have to use the list() function to make them look readable and pretty. You can directly iterate on them.

Next Lesson:

filter() function

Roger Arndt - Moonlit-Retreat


Roger Arndt

Moonlit Retreat

Moonlit Retreat by Roger Arndt