Chapter 3
We'll almost always use tuples (and namedtuples) in the context of a collection of
values. If we're working with single values, or a tidy group of exactly two values, we'll
usually use named parameters to a function. When working with collections, however,
we might need to have iterable-of-tuples or iterable-of-namedtuple constructs.
The decision to use a tuple or namedtuple object is entirely a matter of convenience.
We might be working with a sequence of values as a three tuple of the form (number,
number, number) assuming that the triple is in red, green, and blue order.
We can use functions to pick a three-tuple apart, as shown in the following
command snippet:
red = lambda color: color[0]
green = lambda color: color[1]
blue = lambda color: color[2]
Or, we might introduce the following command line:
Color = namedtuple("Color", ("red", "green", "blue", "name"))
This allows us to use item.red instead of red(item).
The functional programming application of tuples centers on the iterable-of-tuple
design pattern. We'll look closely at a few iterable-of-tuple techniques. We'll look
at the namedtuple techniques in Chapter 7, Additional Tuple Techniques.
Using generator expressions
We've shown some examples of generator expressions already. We'll show many
more later in the chapter. We'll introduce some more sophisticated generator
techniques in this section.
We need to mention a small bit of Python syntax here. It's common to see generator
expressions used to create the list or dict literals via a list comprehension or a
dict comprehension. For our purposes, a list display (or comprehension) is just one
use of generator expressions. We can try to make a distinction between generator
expressions outside a display and generator expressions inside a display, but
there's nothing to be gained by this. The syntax is the same except for the enclosing
punctuation and the semantics are indistinguishable.