[Python-ideas] get method for sets?

Ben Finney ben+python at benfinney.id.au
Wed May 16 09:39:10 CEST 2012


Mike Meyer <mwm at mired.org> writes:

> 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.

With a mapping, you use a key to get an item.

With a sequence, you have an index and get an item.

Sets are unordered collections of items without indices or keys. What
does it mean to you to “get” an item from that?

If you mean “get the items one by one”, a set is an iterable::

    for item in foo_set:
        do_something_with(item)

If you mean “test whether an item is in the set”, the ‘in’ operator
works::

    if item in foo_set:
        do_something()

If you mean “get a specific item from a set”, the only way to do that is
to *already have* the specific item and test whether it's in the set.

> 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.

If by “get” you mean to get an *arbitrary* item, not a specific item,
then what's the problem? You already have ‘set.pop’, as you point out.

What need do you have that isn't being fulfilled by the existing mthods
and operators? Can you show some actual code that would be improved by a
‘get’ operation on sets?

-- 
 \          “It's a terrible paradox that most charities are driven by |
  `\     religious belief.… if you think altruism without Jesus is not |
_o__)          altruism, then you're a dick.” —Tim Minchin, 2010-11-28 |
Ben Finney




More information about the Python-ideas mailing list