Getting the member of a singleton set

A

Arnaud Delobelle

Hi all,

I often find myself needing to get (non-destructively) the value of
the member of a singleton set. Is there a good way to do this (as an
expression?) None of the ones I can think of satisfy me, eg:

* list(myset)[0]
* iter(myset).next()
* set(myset).pop()

What I would like is something like a 'peek()' function or method
(would return the same as pop() but wouldn't pop anything). I would
like to know of a better idiom if it exists. If not, isn't there a
need for one?

Note: it is comparatively easier to do this destructively:
myset.pop()
or to bind a name to the member:
element, = myset

PS: this problem is not restricted to sets but could occur with many
'container' types.
 
G

Gabriel Genellina

En Sun, 20 May 2007 17:27:20 -0300, Arnaud Delobelle
Hi all,

I often find myself needing to get (non-destructively) the value of
the member of a singleton set. Is there a good way to do this (as an
expression?) None of the ones I can think of satisfy me, eg:

* list(myset)[0]
* iter(myset).next()
* set(myset).pop()

What I would like is something like a 'peek()' function or method
(would return the same as pop() but wouldn't pop anything). I would
like to know of a better idiom if it exists. If not, isn't there a
need for one?

Yes, something like peek() or any() would be useful. But you're not
restricted by the builtin methods, you could write your own:

def peek(iterable):
return iter(iterable).next()

maybe converting the possible StopIteration into another exception like
EmptyContainer(ValueError).
Note: it is comparatively easier to do this destructively:
myset.pop()
or to bind a name to the member:
element, = myset

If you know that your set contains exactly one element, I like the later
form.
PS: this problem is not restricted to sets but could occur with many
'container' types.

Yes, and I've seen all your expressions, plus some more, like: for x in
container: break
All of them are rather ugly...
 
A

Arnaud Delobelle

On May 21, 12:52 am, "Gabriel Genellina" <[email protected]>
wrote:
[...]
Yes, something like peek() or any() would be useful. But you're not
restricted by the builtin methods, you could write your own:

def peek(iterable):
return iter(iterable).next()

Yes, but that's not getting rid of the ugliness, just tucking away
from sight :) *I* would know it's still there.
IMHO a 'peek' method in these container types (maybe not all iterables
because in some cases iter(it).next() changes the state of it, eg when
it is an iterator itself).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,433
Messages
2,571,683
Members
48,796
Latest member
Greg L.

Latest Threads

Top