O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required