[Python-ideas] get method for sets?

Bruce Leban bruce at leapyear.org
Wed May 16 09:02:31 CEST 2012


On Tue, May 15, 2012 at 11:32 PM, Mike Meyer <mwm at mired.org> wrote:

> Is there some reason that there isn't a straightforward way to get an
> element from a set without removing it? Everything I find either
> requires multiple statements or converting the set to another data
> type.
>
> It seems that some kind of get method would be useful. The argument
> that "getting an arbitrary element from a set isn't useful" is refuted
> by 1) the existence of the pop method, which does just that, and 2)
> the fact that I (and a number of other people) have run into such a
> need.
>

Your request needs clarification.  What does set.get do? What is the actual
use case? I understand what pop does: it removes and returns an arbitrary
member of the set. Therefore, if I call pop repeatedly, I eventually get
all the members. That's useful.

Here's one definition of get:

def get_from_set1(s):
    """Return an arbitrary member of a set."""
    return min(s, key=hash)


How is this useful?

Or do you mean instead: checks to see if an element is in the set and
returns it otherwise returns a default value

def get_from_set2(s, v, d=None):
    """Returns v if v is in the set, otherwise returns d."""
    return v if v in s else d

I suppose this could be useful but it's a one liner and seems much less
obvious what it does than dict.get.

Or did you mean something else?

--- Bruce
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120516/290a49c2/attachment.html>


More information about the Python-ideas mailing list