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".)
set
is not ordered.list
s and tuple
s are ordered.Is there a generic test that I can use?
Yes, the order of elements in a python list is persistent. Show activity on this post. A list is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so.
The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator.
Definition and Usage. The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With