So far, we have seen two kinds of sequence object: strings and lists. Another kind of sequence is called a tuple. Tuples are formed with the comma operator , and typically enclosed using parentheses. We've actually seen them in the previous chapters, and sometimes referred to them as "pairs," since there were always two members. However, tuples can have any number of members. Like lists and strings, tuples can be indexed © and sliced ©, and have a length O.

>>> t[0] 0 'walk' >>> t[1:] 0 ('fem', 3) >>> len(t) O


Tuples are constructed using the comma operator. Parentheses are a more general feature of Python syntax, designed for grouping. A tuple containing the single element 'snark' is defined by adding a trailing comma, like this: 'snark',. The empty tuple is a special case, and is defined using empty parentheses ().

Let's compare strings, lists, and tuples directly, and do the indexing, slice, and length operation on each type:

>>> text = ['I', 'turned', 'off', 'the', 'spectroroute']

('ute', ['off', 'the', 'spectroroute'], (6, 'turned'))

Notice in this code sample that we computed multiple values on a single line, separated by commas. These comma-separated expressions are actually just tuples—Python allows us to omit the parentheses around tuples if there is no ambiguity. When we print a tuple, the parentheses are always displayed. By using tuples in this way, we are implicitly aggregating items together.

Your Turn: Define a set, e.g., using set(text), and see what happens when you convert it to a list or iterate over its members.

Was this article helpful?

0 0

Post a comment