Best way to extract an item from a set of len 1

Alex Martelli aleax at mail.comcast.net
Wed Jan 25 10:13:47 EST 2006


Tim Chase <python.list at tim.thechases.com> wrote:
   ...
> To get the item, i had to resort to methods that feel less than 
> the elegance I've come to expect from python:
> 
>       >>> item = [x for x in s][0]

A shorter, clearer expression of the same idea:

item = list(s)[0]

or

item = list(s).pop()

> or the more convoluted two-step
> 
>       >>> item = s.pop()
>       >>> s.add(item)

which in turn suggests

item = set(s).pop()

Similar ideas include iter(s).next() and s.copy().pop().

Basically: s has no way to get the item non-destructively, so, either
make a copy (and use the destructive-get 'pop' on the copy) or build
from s a type which DOES have ways to get the item (iterator, list, etc)
be they destructive or not.  As for speed, measuring is the only way,
and timeit is your friend.  As for elegance, the most concise readable
form is "set(s).pop()" and that's what I would use.


Alex





More information about the Python-list mailing list