Skip to content

ordered_set

Ordered set implementation maintaining insertion order.

This module provides an OrderedSet class that combines set semantics (uniqueness) with list semantics (insertion order preservation).

OrderedSet

A set that maintains insertion order of elements.

Supports standard set operations (add, remove, discard, pop, clear) and set algebra (union, intersection, difference). Iteration yields elements in insertion order.

Example
oset = ordered_set.OrderedSet(['b', 'a', 'b', 'c'])
list(oset)  # ['b', 'a', 'c'] - duplicates keep their first position.
oset.add('x')  # Newly added values are appended at the end.
oset.union(['x', 'y'])  # Order of the result follows this set.
Source code in py_misc_utils/ordered_set.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
class OrderedSet:
  """A set that maintains insertion order of elements.

  Supports standard set operations (add, remove, discard, pop, clear)
  and set algebra (union, intersection, difference).
  Iteration yields elements in insertion order.

  Example:
    oset = ordered_set.OrderedSet(['b', 'a', 'b', 'c'])
    list(oset)  # ['b', 'a', 'c'] - duplicates keep their first position.
    oset.add('x')  # Newly added values are appended at the end.
    oset.union(['x', 'y'])  # Order of the result follows this set.
  """

  def __init__(self, init=None):
    """Initialize an ordered set.

    Args:
      init: Optional iterable of initial values.
    """
    self._data = dict()
    self._seqno = 0

    for value in init or ():
      self.add(value)

  def add(self, value):
    """Add a value to the set.

    Args:
      value: Value to add.

    Returns:
      The sequence number assigned to this value (0 for first, etc.).
      Returns existing sequence number if value already present.
    """
    n = self._data.get(value)
    if n is None:
      self._data[value] = n = self._seqno
      self._seqno += 1

    return n

  def remove(self, value):
    """Remove a value from the set (KeyError if missing).

    Args:
      value: Value to remove.

    Raises:
      KeyError: If value is not in the set.
    """
    self._data.pop(value)

  def discard(self, value):
    """Remove a value from the set if present.

    Args:
      value: Value to remove (no error if absent).
    """
    self._data.pop(value, None)

  def pop(self):
    """Remove and return the most recently added value.

    Returns:
      The most recently added value.

    Raises:
      KeyError: If the set is empty.
    """
    value, _ = self._data.popitem()

    return value

  def clear(self):
    """Remove all values from the set."""
    self._data = dict()
    self._seqno = 0

  def __len__(self):
    """Return the number of elements in the set."""
    return len(self._data)

  def values(self):
    """Iterate over values in insertion order.

    Returns:
      Generator yielding values in order of insertion.
    """
    return (y[0] for y in sorted(self._data.items(), key=lambda x: x[1]))

  def __iter__(self):
    """Iterate over values in insertion order."""
    return iter(self.values())

  def __contains__(self, value):
    """Check if a value is in the set."""
    return value in self._data

  def __copy__(self):
    """Copy protocol implementation: clone the internal state.

    Returns:
      New OrderedSet with the same elements and order, holding its own
      internal state.
    """
    nos = OrderedSet()
    nos._data = self._data.copy()
    nos._seqno = self._seqno

    return nos

  def copy(self):
    """Create a shallow copy of the ordered set.

    Returns:
      New OrderedSet with the same elements and order, holding its own
      internal state.
    """
    return copy.copy(self)

  def union(self, *others):
    """Return the union of this set with others.

    Args:
      *others: Other iterables to union with.

    Returns:
      New OrderedSet containing all unique elements, preserving order
      from this set followed by new elements from others.
    """
    nos = copy.copy(self)
    for other in others:
      for value in other:
        nos.add(value)

    return nos

  def intersection(self, *others):
    """Return the intersection of this set with others.

    Args:
      *others: Other iterables to intersect with.

    Returns:
      New OrderedSet containing only elements present in all sets,
      preserving order from this set.
    """
    nos = OrderedSet()
    for value in self.values():
      if all(value in other for other in others):
        nos.add(value)

    return nos

  def difference(self, *others):
    """Return the difference of this set with others.

    Args:
      *others: Other iterables to subtract.

    Returns:
      New OrderedSet containing elements in this set but not in any
      of the others, preserving order from this set.
    """
    nos = OrderedSet()
    for value in self.values():
      if not any(value in other for other in others):
        nos.add(value)

    return nos

add(value)

Add a value to the set.

Parameters:

Name Type Description Default
value

Value to add.

required

Returns:

Type Description

The sequence number assigned to this value (0 for first, etc.).

Returns existing sequence number if value already present.

Source code in py_misc_utils/ordered_set.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def add(self, value):
  """Add a value to the set.

  Args:
    value: Value to add.

  Returns:
    The sequence number assigned to this value (0 for first, etc.).
    Returns existing sequence number if value already present.
  """
  n = self._data.get(value)
  if n is None:
    self._data[value] = n = self._seqno
    self._seqno += 1

  return n

remove(value)

Remove a value from the set (KeyError if missing).

Parameters:

Name Type Description Default
value

Value to remove.

required

Raises:

Type Description
KeyError

If value is not in the set.

Source code in py_misc_utils/ordered_set.py
53
54
55
56
57
58
59
60
61
62
def remove(self, value):
  """Remove a value from the set (KeyError if missing).

  Args:
    value: Value to remove.

  Raises:
    KeyError: If value is not in the set.
  """
  self._data.pop(value)

discard(value)

Remove a value from the set if present.

Parameters:

Name Type Description Default
value

Value to remove (no error if absent).

required
Source code in py_misc_utils/ordered_set.py
64
65
66
67
68
69
70
def discard(self, value):
  """Remove a value from the set if present.

  Args:
    value: Value to remove (no error if absent).
  """
  self._data.pop(value, None)

pop()

Remove and return the most recently added value.

Returns:

Type Description

The most recently added value.

Raises:

Type Description
KeyError

If the set is empty.

Source code in py_misc_utils/ordered_set.py
72
73
74
75
76
77
78
79
80
81
82
83
def pop(self):
  """Remove and return the most recently added value.

  Returns:
    The most recently added value.

  Raises:
    KeyError: If the set is empty.
  """
  value, _ = self._data.popitem()

  return value

clear()

Remove all values from the set.

Source code in py_misc_utils/ordered_set.py
85
86
87
88
def clear(self):
  """Remove all values from the set."""
  self._data = dict()
  self._seqno = 0

values()

Iterate over values in insertion order.

Returns:

Type Description

Generator yielding values in order of insertion.

Source code in py_misc_utils/ordered_set.py
 94
 95
 96
 97
 98
 99
100
def values(self):
  """Iterate over values in insertion order.

  Returns:
    Generator yielding values in order of insertion.
  """
  return (y[0] for y in sorted(self._data.items(), key=lambda x: x[1]))

copy()

Create a shallow copy of the ordered set.

Returns:

Type Description

New OrderedSet with the same elements and order, holding its own

internal state.

Source code in py_misc_utils/ordered_set.py
123
124
125
126
127
128
129
130
def copy(self):
  """Create a shallow copy of the ordered set.

  Returns:
    New OrderedSet with the same elements and order, holding its own
    internal state.
  """
  return copy.copy(self)

union(*others)

Return the union of this set with others.

Parameters:

Name Type Description Default
*others

Other iterables to union with.

()

Returns:

Type Description

New OrderedSet containing all unique elements, preserving order

from this set followed by new elements from others.

Source code in py_misc_utils/ordered_set.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def union(self, *others):
  """Return the union of this set with others.

  Args:
    *others: Other iterables to union with.

  Returns:
    New OrderedSet containing all unique elements, preserving order
    from this set followed by new elements from others.
  """
  nos = copy.copy(self)
  for other in others:
    for value in other:
      nos.add(value)

  return nos

intersection(*others)

Return the intersection of this set with others.

Parameters:

Name Type Description Default
*others

Other iterables to intersect with.

()

Returns:

Type Description

New OrderedSet containing only elements present in all sets,

preserving order from this set.

Source code in py_misc_utils/ordered_set.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def intersection(self, *others):
  """Return the intersection of this set with others.

  Args:
    *others: Other iterables to intersect with.

  Returns:
    New OrderedSet containing only elements present in all sets,
    preserving order from this set.
  """
  nos = OrderedSet()
  for value in self.values():
    if all(value in other for other in others):
      nos.add(value)

  return nos

difference(*others)

Return the difference of this set with others.

Parameters:

Name Type Description Default
*others

Other iterables to subtract.

()

Returns:

Type Description

New OrderedSet containing elements in this set but not in any

of the others, preserving order from this set.

Source code in py_misc_utils/ordered_set.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def difference(self, *others):
  """Return the difference of this set with others.

  Args:
    *others: Other iterables to subtract.

  Returns:
    New OrderedSet containing elements in this set but not in any
    of the others, preserving order from this set.
  """
  nos = OrderedSet()
  for value in self.values():
    if not any(value in other for other in others):
      nos.add(value)

  return nos