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

The iter() function with a sentinel value


The built-in iter() function creates an iterator over an object of one of the collection classes. The list, dict, and set classes all work with the iter() function to provide an iterator object for the items in the underlying collection. In most cases, we'll allow the for statement to do this implicitly. In a few cases, however, we need to create an iterator explicitly. One example of this is to separate the head from the tail of a collection. 

Other uses include building iterators to consume the values created by a callable object (for example, a function) until a sentinel value is found. This feature is sometimes used with the read() function of a file to consume items until some end-of-line or end-of-file sentinel value is found. An expression such as iter(file.read, '\n') will evaluate the given function until the sentinel value, '\n', is found. This must be used carefully: if the sentinel is not found, it can continue reading zero-length strings...