Tuples

The last collection type in our survey is the Python tuple. Tuples construct simple groups of objects. They work exactly like lists, except that tuples can’t be changed in-place (they’re immutable) and are usually written as a series of items in parentheses, not square brackets. Although they don’t support as many methods, tuples share most of their properties with lists. Here’s a quick look at the basics. Tuples are:

Ordered collections of arbitrary objects

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Like strings and lists, tuples are positionally ordered collections of objects (i.e., they maintain a left-to-right order among their contents); like lists, they can embed any kind of object.

Accessed by offset

Like strings and lists, items in a tuple are accessed by offset (not by key); they support all the offset-based access operations, such as indexing and slicing.

Of the category “immutable sequence”

Like strings and lists, tuples are sequences; they support many of the same operations. However, like strings, tuples are immutable; they don’t support any of the in-place change operations applied to lists.

Fixed-length, heterogeneous, and arbitrarily nestable

Because tuples are immutable, you cannot change the size of a tuple without making a copy. On the other hand, tuples can hold any type of object, including other compound objects (e.g., lists, dictionaries, other tuples), and so support arbitrary nesting.

Arrays of object references

Like lists, tuples are best thought of as object reference arrays; tuples store access points to other objects (references), and indexing a tuple is relatively quick.

Table 9-1 highlights common tuple operations. A tuple is written as a series of objects (technically, expressions that generate objects), separated by commas and normally enclosed in parentheses. An empty tuple is just a parentheses pair with nothing inside.

Table 9-1. Common tuple literals and operations

Operation

Interpretation

()

An empty tuple

T = (0,)

A one-item tuple (not an expression)

T = (0, 'Ni', 1.2, 3)

A four-item tuple

T = 0, 'Ni', 1.2, 3

Another four-item tuple (same as prior line)

T = ('abc', ('def', 'ghi'))

Nested tuples

T = tuple('spam')

Tuple of items in an iterable

T[i]

T[i][j]

T[i:j]

len(T)

Index, index of index, slice, length

T1 + T2

T * 3

Concatenate, repeat

for x in T: print(x)

'spam' in T

[x ** 2 for x in T]

Iteration, membership

T.index('Ni')

T.count('Ni')

Methods in 2.6 and 3.0: search, count