Functional Python Programming

(Wang) #1

Working with Collections


The following are three examples to clarify the use of the next() and iter()
functions:





list(legs(x for x in range(3)))
[(0, 1), (1, 2)]
list(legs([0,1,2]))
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in legs
TypeError: 'list' object is not an iterator
list(legs( iter([0,1,2])))
[(0, 1), (1, 2)]





In the first case, we applied the legs() function to an iterable. In this case, the
iterable was a generator expression. This is the expected behavior based on our
previous examples in this chapter. The items are properly paired up to create two
legs from three waypoints.


In the second case, we tried to apply the legs() function to a sequence. This resulted
in an error. While a list object and an iterable are equivalent when used in a for
statement, they aren't equivalent everywhere. A sequence isn't an iterator; it doesn't
implement the next() function. The for statement handles this gracefully, however,
by creating an iterator from a sequence automatically.


To make the second case work, we need to explicitly create an iterator from a list
object. This permits the legs() function to get the first item from the iterator over
the list items.


Extending a simple loop


We have two kinds of extensions we might factor into a simple loop. We'll look
first at a filter extension. In this case, we might be rejecting values from further
consideration. They might be data outliers, or perhaps source data that's improperly
formatted. Then, we'll look at mapping source data by performing a simple
transformation to create new objects from the original objects. In our case, we'll be
transforming strings to floating-point numbers. The idea of extending a simple
loop with a mapping, however, applies to situations. We'll look at refactoring the
above pairs() function. What if we need to adjust the sequence of points to discard
a value? This will introduce a filter extension that rejects some data values.


As the loop we're designing simply returns pairs without performing any additional
application-related processing, the complexity is minimal. Simplicity means we're
somewhat less likely to confuse the processing state.

Free download pdf