Skip to Content
Python: Essential Reference, Third Edition
book

Python: Essential Reference, Third Edition

by David Beazley
February 2006
Intermediate to advanced content levelIntermediate to advanced
648 pages
14h 53m
English
Sams
Content preview from Python: Essential Reference, Third Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python: Essential Reference

Python: Essential Reference

David M. Beazley

Publisher Resources

ISBN: 0672328623Purchase book