[Python-ideas] get method for sets?

Mike Meyer mwm at mired.org
Wed May 16 09:40:34 CEST 2012


On Wed, 16 May 2012 00:02:31 -0700
Bruce Leban <bruce at leapyear.org> wrote:
> 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.

So is just getting a single member:

> Here's one definition of get:
> def get_from_set1(s):
>     """Return an arbitrary member of a set."""
>     return min(s, key=hash)

From poking around, at least at one time the fastest implementation
was the very confusing:

def get_from_set(s):
    for x in s:
    	return x

> How is this useful?

Basically, anytime you want to examine an arbitrary element of a set,
and would use pop, except you need to preserve the set for future
use. In my case, I'm running a series of tests on the set, and some
tests need an element.

Again, looking for a reason for this not existing turned up other
cases where people were wondering how to do this.

Hmm. Maybe the name should be item?

	 <mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/
Independent Software developer/SCM consultant, email for more information.

O< ascii ribbon campaign - stop html mail - www.asciiribbon.org



More information about the Python-ideas mailing list