Book Image

Functional Python Programming

By : Steven F. Lott, Steven F. Lott
Book Image

Functional Python Programming

By: Steven F. Lott, Steven F. Lott

Overview of this book

Table of Contents (23 chapters)
Functional Python Programming
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using the operator module instead of lambdas


When using the max(), min(), and sorted() functions, we have an optional key= parameter. The function provided as an argument value modifies the behavior of the higher-order function. In many cases, we used simple lambda forms to pick items from a tuple. Here are two examples we heavily relied on:

fst = lambda x: x[0]
snd = lambda x: x[1]

These match built-in functions in other functional programming languages.

We don't really need to write these functions. There's a version available in the operator module which describes these functions.

Here's some sample data we can work with:

>>> year_cheese = [(2000, 29.87), (2001, 30.12), (2002, 30.6), (2003, 30.66), (2004, 31.33), (2005, 32.62), (2006, 32.73), (2007, 33.5), (2008, 32.84), (2009, 33.02), (2010, 32.92)]

This is the annual cheese consumption. We used this example in Chapter 2, Introducing Some Functional Features and Chapter 9, More Itertools Techniques.

We can locate the data point...