Add `OrderedSet` to stdlib

A couple people have asked now about the practical applications of an ordered set. Me and @jagerber have already shared our 3 personal, unique uses cases for OrderedSet. To summarise them:

  • It is a good choice as the backing collection for the observer pattern.

  • It can be used in seen.add(idn) style algorithms to limit the size of the seen set by pruning earlier items.

  • It is useful for various user input processing applications in order to give users a ‘consistent and predictable’ display.

I would also like to highlight another use case: how to remove duplicates from a list while preserving order.

  • Removing duplicates from a list: list(set(lst)).

  • Removing duplicates from a list while preserving order: list(dict.fromkeys(lst)).

  • Removing duplicates from a list while preserving order, using OrderedSet: list(OrderedSet(lst)).

So with OrderedSet we gain a more obvious way to solve this common problem. We no longer need to go from set to dict; we can simply think in sets now.

I would also like to reiterate the non-practical applications of adding OrderedSet:

  • It sits nicely next to OrderedDict.

  • The implementation is easy because it can piggy pack off of dict which is ordered.

  • Java has an ordered set (LinkedHashSet).

6 Likes