Functional Python Programming

(Wang) #1

Additional Tuple Techniques


Using an immutable namedtuple as a record


In Chapter 3, Functions, Iterators, and Generators, we showed two common techniques
to work with tuples. We've also hinted at a third way to handle complex structures.
We can do any of the following, depending on the circumstances:



  • Use lambdas (or functions) to select a named item using the index

  • Use lambdas (or functions) with *parameter to select an item by parameter
    name, which maps to an index

  • Use namedtuples to select an item by attribute name or index


Our trip data, introduced in Chapter 4, Working with Collections, has a rather complex
structure. The data started as an ordinary time series of position reports. To compute
the distances covered, we transposed the data into a sequence of legs with a start
position, end position, and distance as a nested three-tuple.


Each item in the sequence of legs looks as follows as a three-tuple:


first_leg= ((37.54901619777347, -76.33029518659048), (37.840832,
-76.273834), 17.7246)


This is a short trip between two points on the Chesapeake Bay.


A nested tuple of tuples can be rather difficult to read; for example, expressions such
as first_leg[0][0] aren't very informative.


Let's look at the three alternatives for selected values out of a tuple. The first technique
involves defining some simple selection functions that can pick items from a tuple by
index position:


start= lambda leg: leg[0]


end= lambda leg: leg[1]


distance= lambda leg: leg[2]


latitude= lambda pt: pt[0]


longitude= lambda pt: pt[1]


With these definitions, we can use latitude(start(first_leg)) to refer to a
specific piece of data.

Free download pdf