Best way to extract an item from a set of len 1
Tim Chase
python.list at tim.thechases.com
Wed Jan 25 09:48:38 EST 2006
When you have a set, known to be of length one, is there a "best"
("most pythonic") way to retrieve that one item?
# given that I've got Python2.3.[45] on hand,
# hack the following two lines to get a "set" object
>>> import sets
>>> set = sets.Set
>>> s = set(['test'])
>>> len(s)
1
>>> s[0]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unindexable object
(which is kinda expected, given that it's unordered...an index
doesn't make much sense)
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]
or the more convoluted two-step
>>> item = s.pop()
>>> s.add(item)
or even worse, intruding into private members
>>> item = s._data.keys()[0]
Is any of these more "pythonic" than the others? Is there a more
elegant 2.3.x solution? If one upgrades to 2.4+, is there
something even more elegant? I suppose I was looking for
something like
>>> item = s.aslist()[0]
which feels a little more pythonic (IMHO). Is one solution
preferred for speed over others (as this is happening in a fairly
deeply nested loop)?
Any tips, preferences, input, suggestions, pointers to obvious
things I've missed, or the like?
Thanks,
-tkc
More information about the Python-list
mailing list