A.6 Tuples

A tuple is a sequence of elements of potentially mixed types. A tuple typically contains unordered, heterogeneous elements akin to a struct in C with the exception that a tuple is indexed by numbers (like a list) rather than by field names (like a struct). Formally, a tuple is an element e of a Cartesian product of a given number of sets: e ∈ (S1 × S2 × … × Sn). A two-element tuple is a called a pair [e.g., e ∈ (A × B)]. A three-element tuple is a called a triple [e.g., e (A × B × C)].

The difference between lists and tuples in Python, which has implications for their usage, can be captured as follows. Tuples are a data structure whose fields are unordered and have different meanings, such that they typically have different types. Lists, by contrast, are ordered sequences of elements, typically of the same type. For instance, a tuple is an appropriate data structure for storing an employee record containing id, name, rate, and a designation of promotion or not. In turn, a company can be represented by a list of these employee tuples ordered by employment date:

A set of four code lines in Python with employee tuples.
Description

It would not be possible or practical to represent this company database as a tuple of lists. Also, note that Python lists are mutable while Python tuples are immutable. Thus, tuples in Python are like lists in Scheme. For example, we could add and remove employees from the company list, but we could not change the rate of an employee. Elements of a tuple are accessed in the same way as elements of a list:

A set of four code lines in Python for accessing the elements of a tuple.
Description

Tuples and lists can also be unpacked into multiple bindings:

A set of five code lines in Python with tuples and lists unpacked into multiple bindings.
Description

Although this situation is rare, the need might arise for a tuple with only one element. Suppose we tried to create a tuple this way:

A set of four code lines in Python for creating a tuple.
Description

The expression (1) does not evaluate to a tuple; instead, it evaluates to the integer 1. Otherwise, this syntax would introduce ambiguity with parentheses in mathematical expressions. However, Python does have a syntax for making a tuple with only one element—insert a comma between the element and the closing parenthesis:

A set of four code lines in Python for making a tuple with only one element.
Description

If a function appears to return multiple values, it actually returns a single tuple containing those values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.160.43