python-sortedcontainers icon indicating copy to clipboard operation
python-sortedcontainers copied to clipboard

ValueError when discarding values with changing sort value

Open gboeer opened this issue 1 year ago • 2 comments
trafficstars

I have the case, that I want to use a custom sort function when working with a SortedSet. The key provided by this function for each value may change, based on some external properties. I now ran into the problem, that when discarding keys from my Set, I get a ValueError:

File "/home/appuser/.pyenv/versions/3.11.7/lib/python3.11/site-packages/sortedcontainers/sortedlist.py", line 2031, in remove
    raise ValueError('{0!r} not in list'.format(value))

To be honest, it took me several hours to figure out the cause of this which I believe is the fact, that the key values may change over time. I reproduced this with a simple example which uses random values:

import random
def compute_gain(value):
    return random.randint(1, 100)

sorted_set = SortedSet(key=compute_gain)
sorted_set.update(range(5))  
sorted_set.discard(sorted_set[-1])  
File "/home/appuser/.pyenv/versions/3.11.7/lib/python3.11/site-packages/sortedcontainers/sortedlist.py", line 2031, in remove
    raise ValueError('{0!r} not in list'.format(value))
ValueError: 0 not in list

I can somewhat understand that this may not be the exact use case intended for the sorted containers, and I could rebuild the whole SortedSet to work around this. However, it isn't really obvious to me why this happens when I just want to discard a value.

gboeer avatar Jun 25 '24 11:06 gboeer