[Python-ideas] get method for sets?

Nick Coghlan ncoghlan at gmail.com
Wed May 16 09:11:28 CEST 2012


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)

Now, at the iterator level, it is possible to turn "do something for
all items in an iterable" to "do something for the *first* item in the
iterable" via "next(iter(obj))".

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)?

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list