O'Reilly logo

Functional Python Programming by Steven Lott

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

Writing higher-order mappings and filters

Python's two built-in higher-order functions, map() and filter(), generally handle almost everything we might want to throw at them. It's difficult to optimize them in a general way to achieve higher performance. We'll look at functions of Python 3.4, such as imap(), ifilter(), and ifilterfalse(), in Chapter 8, The Itertools Module.

We have three largely equivalent ways to express a mapping. Assume that we have some function, f(x), and some collection of objects, C. We have three entirely equivalent ways to express a mapping; they are as follows:

  • The map() function:
    map(f, C)
  • The generator expression:
    (f(x) for x in C)
  • The generator function:
    def mymap(f, C):
        for x in C:
            yield f(x)
    mymap(f, C)

Similarly, we have ...

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