Book Image

Functional Python Programming - Second Edition

By : Steven F. Lott
Book Image

Functional Python Programming - Second Edition

By: Steven F. Lott

Overview of this book

If you’re a Python developer who wants to discover how to take the power of functional programming (FP) and bring it into your own programs, then this book is essential for you, even if you know next to nothing about the paradigm. Starting with a general overview of functional concepts, you’ll explore common functional features such as first-class and higher-order functions, pure functions, and more. You’ll see how these are accomplished in Python 3.6 to give you the core foundations you’ll build upon. After that, you’ll discover common functional optimizations for Python to help your apps reach even higher speeds. You’ll learn FP concepts such as lazy evaluation using Python’s generator functions and expressions. Moving forward, you’ll learn to design and implement decorators to create composite functions. You'll also explore data preparation techniques and data exploration in depth, and see how the Python standard library fits the functional programming model. Finally, to top off your journey into the world of functional Python, you’ll at look at the PyMonad project and some larger examples to put everything into perspective.
Table of Contents (22 chapters)
Title Page
Packt Upsell
Contributors
Preface
Index

Using map() with multiple sequences


Sometimes, we'll have two collections of data that need to be parallel to each other. In Chapter 4, Working with Collections, we saw how the zip() function can interleave two sequences to create a sequence of pairs. In many cases, we're really trying to do something like the following:

map(function, zip(one_iterable, another_iterable))  

We're creating argument tuples from two (or more) parallel iterables and applying a function to the argument tuple. We can also look at it as follows:

(function(x,y) 
    for x,y in zip(one_iterable, another_iterable)
)

Here, we've replaced the map() function with an equivalent generator expression.

We might have the idea of generalizing the whole thing to the following:

def star_map(function, *iterables)
    return (function(*args) for args in zip(*iterables))

There is a better approach that is already available to us. We don't actually need these techniques. Let's look at a concrete example of the alternate approach.

In Chapter...