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!
- OS operating system module using path parameter.
- Find the smallest and largest integers after sorting using bubble sort.
- Find the integer and its number of occurrences.
- Algorithm complexity – Big O Notation with Examples.
- Linear search.
- Map module using series mapping and parallel mapping.
- Mapping and Transposing with Map Module.
- Map Module/built-in Function.
- Linux commands for managing files.
- Program which takes two lists and maps two lists into a dictionary.
- Splitting strings and substituting using regular expressions regex.
- Basics of regular expression Regex.
- Find the square value of the dictionary.
- Check whether the given key is present in the dictionary.
- Matching an expression only in specific places using regular expressions.
- Escaping special characters using regular expressions.
- Check the key.
- Grouping and sub-grouping using regular expressions.
- Generate a Dictionary that Contains Numbers in the Form (x , x*x).
- Algorithm complexity Big-Theta, Big-Omega and Big-O Notations.