map(), zip(), reduce(), and filter()
The t = map(func, s) function applies the function func to each of the elements in s and returns a new list, t. Each element of t is t[i] = func(s[i]). The function given to map() should require only one argument. For example:
a = [1, 2, 3, 4, 5, 6] def foo(x): return 3*x b = map(foo,a) # b = [3, 6, 9, 12, 15, 18]
Alternatively, this could be calculated using an anonymous function, as follows:
b = map(lambda x: 3*x, a) # b = [3, 6, 9, 12, 15, 18]
The map() function can also be applied to multiple lists, such as t = map(func, s1, s2, ..., sn). In this case, each element of t is t[i] = func(s1[i], s2[i], ..., sn[i]), and the function given to map() must accept the same number of arguments as the number of ...
Get Python: Essential Reference, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.