Menu Close

Map Module/built-in Function

The map function is the simplest one among Python built-ins used for functional programming. map() applies a specified function to each element in an iterable :

anime = ['Naruto', 'Bleach', 'One Piece']
print(map(len, anime))

#Output:  <map object at 0x7f94e082b0f0>

The result can be explicitly converted to a list.

anime = ['Naruto', 'Bleach', 'One Piece']
List_1 = list(map(len, anime))

print(List_1)

#Output:  [6, 6, 9]

map() can be replaced by an equivalent list comprehension or generator expression: ( Python 3 )

map_is = (len(series) for series in anime)

print(map_is)


#Output:  <generator object <genexpr> at 0x7f601f567360>

Mapping each value in an iterable

For example, you can take the absolute value of each element:

L = list(map(abs, (13, -12, 24, -20, 32, -23)))

print(L)

#Output:  [13, 12, 24, 20, 32, 23]

Anonymous function also support for mapping a list:

L = map(lambda x:x*2, [11, 22, 33, 44, 55])

print(list(L))

#Output:  [22, 44, 66, 88, 110]

or converting decimal values to percentages:

def to_percent(num):
    return num * 100

L = list(map(to_percent, [0.85, 0.95, 1.51, 1.01]))

print(L)


#Output:  [85.0, 95.0, 151.0, 101.0]

or converting dollars to euros (given an exchange rate):

from functools import partial
from operator import mul
rate = 0.9 # fictitious exchange rate
dollars = {'Curtain': 1000, 'jeans': 45, 'Wallet': 5000}

L = sum(map(partial(mul, rate), dollars.values()))

print(L)

#Output:  5440.5

functools.partial is a convenient way to fix parameters of functions so that they can be used with map instead of using lambda or creating customized functions.


Morae Q!

  1. OS operating system module using path parameter.
  2. Find the smallest and largest integers after sorting using bubble sort.
  3. Find the integer and its number of occurrences.
  4. Algorithm complexity – Big O Notation with Examples.
  5. Linear search.
  6. Map module using series mapping and parallel mapping.
  7. Mapping and Transposing with Map Module.
  8. Map Module/built-in Function.
  9. Linux commands for managing files.
  10. Program which takes two lists and maps two lists into a dictionary.
  11. Splitting strings and substituting using regular expressions regex.
  12. Basics of regular expression Regex.
  13. Find the square value of the dictionary.
  14. Check whether the given key is present in the dictionary.
  15. Matching an expression only in specific places using regular expressions.
  16. Escaping special characters using regular expressions.
  17. Check the key.
  18. Grouping and sub-grouping using regular expressions.
  19. Generate a Dictionary that Contains Numbers in the Form (x , x*x).
  20. Algorithm complexity Big-Theta, Big-Omega and Big-O Notations.