Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a Python collection is ordered?

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?

like image 350
bers Avatar asked Dec 11 '20 15:12

bers


People also ask

Is there an ordered list in Python?

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.

How do you check if a list is in ascending or descending order in Python?

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.

What does Order () do in Python?

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.


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
like image 189
user2390182 Avatar answered Oct 04 '22 23:10

user2390182