[Python-ideas] get method for sets?

Mike Meyer mwm at mired.org
Wed May 16 10:09:41 CEST 2012


On Wed, 16 May 2012 17:11:28 +1000
Nick Coghlan <ncoghlan at gmail.com> wrote:

> On Wed, May 16, 2012 at 4: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.
> > My search for such a reason kept finding people asking how
> > to get an element instead. Of course, my key words (set and get) are
> > heavily overloaded.
> The two primary use cases handled by the current interface are:
> 1. Do something for all items in the set (iteration)
> 2. Do something for an arbitrary item in the set, and keep track of
> which items remain (set.pop)

Neither of which fits my use case.

> Since this use case is already covered by the iterator protocol, the
> question then becomes: Is there a specific reason a dedicated
> set-specific solution is needed rather than better educating people
> that "the first item" is an acceptable answer when the request is for
> "an arbitrary item" (this is particularly true in a world where set
> ordering is randomised by default)?

Because next(iter(s)) makes the reader wonder "Why is this iterator
being created?" It's a less expensive form of writing list(s)[0]. It's
also sufficiently non-obvious that the closest I found on google for a
discussion of the issue was the "for x in s: break" variant. Which
makes me think that at the very least, this idiom ought to be
mentioned in the documentation. Or if it's already there, then a
pointer added to the set documentation.

But my question was actually whether or not there was a reason for it
not existing. Has there been a previous discussion of this?

   <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