Lesson 13: map() | Learn and Practice with HolyPython.com (original) (raw)

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. But we’re getting ahead of ourselves. You’ll see the Python examples below.

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.

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.

Notes before map examples:

* It’s good to know different Python objects when working with iterables and functions (list comprehension, dict comprehension, map, filter, zip etc.) as these work in harmony.

Usually in programming, there are multiple ways to achieve a result, and particularly so with Python. So, it’s important to have good command of the syntax and functions especially in the beginning of a journey of programming language learning and practice a lot. But there are many concepts so don’t overwhelm yourself either. One step at a time, you will be an amazing Python programmer.

Below you will find some Python map function examples we have created for you. These Python examples can hopefully make these concepts more clear in a demonstrative way.

** Most examples will make use of list function for data conversion. This is because map function returns a map object (which may look weird). It’s an efficient memory address representation. list function will be used to convert it to an actual list in most of the examples.

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() with len

lst = ["Greenland", "Japan", "Taiwan", "Botswana", "Bhutan", "Tuvalu"]
lst2 = map(len, lst)
print(list(lst2))

Example 2: map() on integers (and floats)

lst = [100,-3.5, 5, -0.7, -9, -0.003]
new_lst = list(map(abs, lst))

print(new_lst)

[100, 3.5, 5, 0.7, 9, 0.003]

Example 3: map() for data type conversion

lst = [87.9983729183943, 88.27381223193, 88.01283119001, 90.3166247903554, 89.94283229101, 100.00000000001]

new_lst = map(int, lst)
print(list(new_lst))

[87, 88, 88, 90, 89, 100]

Example 4: map() with reversed

lst = ["Greenland", "Japan", "Taiwan", "Botswana", "Bhutan", "Tuvalu"]
new_lst = map(reversed, lst)

print(list(new_lst))

[reversed object at 0x000001C05F984F48,
reversed object at 0x000001C05F984588, reversed object at 0x000001C05F984408,
reversed object at 0x000001C05F984D08, reversed object at 0x000001C05F984E08,
reversed object at 0x000001C05F98F548]

lst = ["Greenland", "Japan", "Taiwan", "Botswana", "Bhutan", "Tuvalu"]
new_lst = map(reversed, lst)

for i in new_lst:
    print("".join(i))

dnalneerG
napaJ
nawiaT
anawstoB
natuhB
ulavuT

Example 5: map() with reversed V2

lst = ["Greenland", "Japan", "Taiwan", "Botswana", "Bhutan", "Tuvalu"]
new_lst = map("".join ,map(reversed, lst))

print(new_lst)

dnalneerG
napaJ
nawiaT
anawstoB
natuhB
ulavuT

Example 6: map() with lambda

lst = ["Suzie@GMAIL.com", "haru@Baidu.com", "LIUWEI@qq.com", "ADAM@Yahoo.COM"]

fnc = lambda x: x.lower()
new_lst = list(map(fnc, lst))

print(new_lst)

[‘suzie@gmail.com’, ‘haru@baidu.com’, ‘liuwei@qq.com’, ‘adam@yahoo.com’]

Tips

* You can combine two maps or a filter and a map for more sophisticated operations.

** Some functions return iterable objects that are hard to read for humans. These structures are extremely efficient and when you print them you just see a memory address like :

Simply convert these objects to suitable Python data structure et voila! It’s readable to humans.

Recommended Reads:

Example 7: filter with map and lambda

lst = [2.54, 4.0, 3.0, 9.95, 5.4]
new_lst = map(lambda x: x/100, lst)

print(list(new_lst))

[0.0254, 0.04, 0.03, 0.09949999999999999, 0.054000000000000006]

Example 8: filter with format

Let’s say you are a quantitative analyst in finance. There are some important price returns in a list but they put the percentage values in there directly. 0.03 instead looks like 3. This will not fly from the execs!

Check out this example.

lst = [2.54, 4.0, 3.0, 9.95, 5.4]
new_lst1 = map("{:,.2f}".format, map(lambda x: x/100, lst))
new_lst2 = map("{:,.2%}".format, map(lambda x: x/100, lst))

print(list(new_lst1))
print(list(new_lst2))

[‘0.03’, ‘0.04’, ‘0.03’, ‘0.10’, ‘0.05’]

[‘2.54%’, ‘4.00%’, ‘3.00%’, ‘9.95%’, ‘5.40%’]

Advanced Concepts (Optional)

* map() and filter() can compliment 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().

** You can also combine functions from imported Python libraries. We will see some cool examples with numerical Python library Numpy!

Example 9: filter with map and lambda

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

print(list(a))

Example 10: map() numpy operations (sqrt)

import numpy as np

lst = [1, 4, 9, 11, 400, 10000]
root_lst = map(np.sqrt, lst)

print(list(root_lst))

[1.0, 2.0, 3.0, 3.3166247903554, 20.0, 100.0]

Example 11: map() numpy operations (square)

import numpy as np

lst = [1, 2, 3, 3.3166247903554, 20, 100]

sq_lst = map(np.square, lst)
print(list(sq_lst))

[1, 4, 9, 11.0, 400, 10000]

filter() function