[Python-ideas] get method for sets?

Steven D'Aprano steve at pearwood.info
Wed May 16 09:26:45 CEST 2012


On Wed, May 16, 2012 at 03:10:35AM -0400, Mike Meyer wrote:

> I guess I should have been explicit about what I'm was asking about.

:)
 
> I'm not asking for set.get(x) that returns "this element", I'm asking
> for set.get() that returns an arbitrary element, like set.pop(), but
> without removing it. It doesn't even need to be the same element that
> set.pop() would return.

Could this helper function not do the job?

def get(s):
    x = s.pop()
    s.add(x)
    return x


Of course, this does not guarantee that repeated calls to get() won't 
return the same result over and over again. If that's unacceptable, 
you'll need to specify what behaviour is acceptable -- i.e. what your 
functional requirements are. E.g.

"I need the element to be selected at random."

"I don't need randomness, returning the elements in some arbitrary 
but deterministic order will do, with no repeats or cycles."

"I don't care whether or not there are repeats, so long as the same 
element is not returned twice in a row."

"Once I've seen every element, I expect get() to raise an exception."

etc.

And I guarantee that whatever your requirements are, other people will 
want something different.

Once you have your requirements, you can start thinking about 
implementation (e.g. how does the set remember which elements have 
already been get'ed?).


> The name is probably a poor choice, but I'm not sure what else it
> should be. pop_without_remove seems a bit verbose, and implies that it
> might return the element a pop would.

Are you suggesting that get() and pop() should not return the same 
element?


-- 
Steven



More information about the Python-ideas mailing list