4. Data Collections#
Python’s data collections are the built‑in container types you use to
store, organize, and operate on groups of values. The four main
collection types are: list, tuple, dictionary, and set.
Also, strings are considered a sequence type (a kind of collection) because they behave like collections of characters, although conceptually, strings are considered primitives, not collections, in many languages other than Python.
range, is debatable as a “collection”; it’s really a lazy sequence
generator, not a traditional data structure. It does like a sequence, so
Python treats it as one. Note that range stores a formula, not data;
it computes values on-demand. Therefore, range is a sequence protocol
implementer, not a data container.
4.1. Collection Types#
Here is a summary of the commonly used data collection types.
Type |
Literal |
Mutable |
Ordered |
Usage |
|---|---|---|---|---|
list |
|
Yes |
Yes |
General, grow/shrink, index/slice. |
tuple |
|
No |
Yes |
Fixed records; hashable if elements are. |
dict |
|
Yes (3.7+) |
Yes |
Key-value mapping. |
set |
|
Yes |
No |
Unique items, math set ops. |
frozenset |
|
No |
No |
Hashable set (e.g., dict keys). |
range |
|
No |
Yes |
Lazy integer sequence. |
str |
|
No |
Yes |
Text |
4.2. Sequence Types#
There are three basic sequence types: list, tuple, and range
objects.
*Since Python 3.7+, dictionaries preserve insertion order, but logically unordered.
Python data collections let you: - model data naturally (ordered records, lookup tables, unique elements), - support iteration and common algorithms, - use methods for adding, removing, searching, and transforming data.
Fig. 4.1 10 Data Structures You Use Daily (bytebytego )#