libb.OrderedSet

class OrderedSet(iterable=None)[source]

Bases: MutableSet

A set that maintains insertion order using a doubly linked list.

Provides set operations while preserving the order elements were added.

Note

Based on Raymond Hettinger’s recipe from ActiveState.

Features:
  • Combines set behavior (unique elements) with list behavior (order preservation)

  • Supports all standard set operations (union, intersection, difference)

  • Maintains insertion order for iteration and representation

Example:

>>> s = OrderedSet('abracadaba')
>>> t = OrderedSet('simsalabim')
>>> (s | t)
OrderedSet(['a', 'b', 'r', 'c', 'd', 's', 'i', 'm', 'l'])
>>> (s & t)
OrderedSet(['a', 'b'])
>>> (s - t)
OrderedSet(['r', 'c', 'd'])
__init__(iterable=None)[source]

Initialize an OrderedSet with optional iterable.

Creates an empty ordered set or populates it from an iterable while preserving insertion order and removing duplicates.

Parameters:

iterable (Iterable[Any]) – Optional sequence of elements to add.

__len__()[source]

Return the number of elements in the set.

Returns:

Count of unique elements.

Return type:

int

__contains__(key)[source]

Check if an element exists in the set.

Parameters:

key (Any) – Element to check for membership.

Returns:

True if the element is in the set.

Return type:

bool

add(key)[source]

Add an element to the end of the set if not already present.

Parameters:

key (Any) – Element to add to the set.

Return type:

None

discard(key)[source]

Remove an element from the set if present.

Does not raise an error if element is not found.

Parameters:

key (Any) – Element to remove.

Return type:

None

__iter__()[source]

Iterate over elements in insertion order.

Returns:

Iterator yielding elements in order of addition.

Return type:

Iterator

__reversed__()[source]

Iterate over elements in reverse insertion order.

Returns:

Iterator yielding elements in reverse order.

Return type:

Iterator

pop(last=True)[source]

Remove and return an element from the set.

Parameters:

last (bool) – If True, remove from end; if False, from beginning.

Return type:

Any

Returns:

The removed element.

Raises:

KeyError – If the set is empty.

__repr__()[source]

Return string representation of the set.

Returns:

String showing class name and ordered elements.

Return type:

str

__eq__(other)[source]

Check equality with another set or OrderedSet.

For OrderedSet comparison, both content and order must match. For regular set comparison, only content is considered.

Parameters:

other (object) – Object to compare with.

Returns:

True if sets are equal.

Return type:

bool