Content · Programming · Python

Python Mapping, MutableMapping, Sequence, and Iterable ABCs

Distinguish read-only mapping contracts from mutable ones.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Distinguish read-only mapping contracts from mutable ones.

What You Will Learn


Mapping supplies key lookup without mutation; MutableMapping adds writes and deletions. Sequence describes ordered indexed access. Iterable only promises that iter(object) can produce an iterator.

Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from collections.abc import Iterable, Mapping, MutableMapping, Sequence
objects = ({'id': 1}, (2, 3), iter([4, 5]))
for value in objects:
    print(isinstance(value, Iterable), isinstance(value, Mapping), isinstance(value, MutableMapping), isinstance(value, Sequence))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: collections.abc.
  • The variable objects holds the result of ({'id': 1}, (2, 3), iter([4, 5])). Later lines use that value or inspect how it changes.
  • The loop demonstrates when each value is processed or when cleanup and exception handling take effect.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

True True True False
True False False True
True False False False

When You Would Use This


This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.

Practice: Modify the Code


Design a function accepting Iterable without assuming indexing is available.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Conflating immutable containers with the abstract protocols they satisfy.
  • Overlooking this documented constraint: iterable only promises that iter(object) can produce an iterator.

Key Takeaways


  • Distinguish read-only mapping contracts from mutable ones.
  • Mapping supplies key lookup without mutation; MutableMapping adds writes and deletions.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.