Chapter 3. Collections
Instances of primitive Python types represent individual values, as we saw in the first chapter. Python also has built-in types that are compound, meaning that they group together multiple objects. These are called collections or containers. The objects in a collection are generally referred to as items or elements. Collections can hold any number of items. Some collection types can even contain items with a mixture of types, including other collections.
There are three categories of built-in collection types in
Python: sets, sequences,
and mappings. Streams are
another kind of collection whose elements form a series in
time, rather than the computer’s memory space. Though they are not formally
recognized in Python, many of Python’s functions and methods—especially
those that manipulate files—implement stream-like behavior. Modules such as
array and collections provide additional collection
types.
The primary distinguishing characteristic of the four collection categories is how individual elements are accessed: sets don’t allow individual access; sequences use numerical indexes; mappings use keys; and streams just provide one address—“next.” Strings straddle the border between primitives and collections, having characteristics of both; when treated as collections they are interpreted as sequences of one-character substrings.
Some types are immutable, meaning that once they are created they cannot be changed: elements may not be added, removed, or reordered. ...