How can I check if a Python collection is ordered?

Viewed 177

I would like to check if a collection that has been passed to a function is ordered, that is, the order of elements is fixed. (I am not talking about "sorted".)

  • A set is not ordered.
  • lists and tuples are ordered.

Is there a generic test that I can use?

1 Answers

Ordered non-mapping collections typically implement the sequence protocol (which is mainly characterized by providing indexed access via a __getitem__ method) and can be type-tested against collections.abc.Sequence:

from collections.abc import Sequence

isinstance(set(), Sequence)
# False
isinstance(list(), Sequence)
# True
isinstance(tuple(), Sequence)
# True

If one were to insist that ordered mappings should be included, i.e. that a dict (ordered as of Python 3.7), you could test against collections.abc.Reversible:

isinstance(set(), Reversible)
# False
isinstance(list(), Reversible)
# True
isinstance(tuple(), Reversible)
# True
isinstance(dict(), Reversible)
# True
Related