Skip to content

Fix pop() corrupting index map when removing non-last element#106

Open
gaoflow wants to merge 1 commit into
rspeer:masterfrom
gaoflow:master
Open

Fix pop() corrupting index map when removing non-last element#106
gaoflow wants to merge 1 commit into
rspeer:masterfrom
gaoflow:master

Conversation

@gaoflow

@gaoflow gaoflow commented Jun 28, 2026

Copy link
Copy Markdown

Fixes #83.

After pop(index) removed an element from the middle of an OrderedSet,
the internal index map (self.map) held stale positions for every
element that shifted down. For example:

a = OrderedSet(["a", "b", "c"])
a.pop(0)     # removes "a"
a.items      # ["b", "c"]  -- correct
a.map        # {"b": 1, "c": 2}  -- still has old indices!
a.index("b") # returns 1 instead of 0
a[1]         # returns "c" instead of "b"

The discard() method already handled this correctly. This PR
brings pop() in line with discard() by rebuilding the map after
removal so that items[i] and map always agree.

Created under human direction with AI assistance.

pop() with a non-default index removed the element from the items list
and the map dict, but did not update the stored indices for every
element that shifted down. After pop(0), subsequent map lookups and
index() calls would return stale positions, breaking the invariant
that items[i] and map[items[i]] always agree.

discard() already handled this correctly.  The fix rebuilds the map
after the removal, keeping items and map consistent.

Fixes rspeer#83
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OrderedSet.pop() with a non-default index breaks the contract

1 participant