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

Peter Otten __peter__ at web.de
Wed Jan 25 10:09:17 EST 2006


Tim Chase wrote:

> When you have a set, known to be of length one, is there a "best"
> ("most pythonic") way to retrieve that one item?
 
>>> s = set(["one-and-only"])
>>> item, = s
>>> item
'one-and-only'

This works for any iterable and guarantees that it contains exactly one
item. The comma may easily be missed, though.

Peter



More information about the Python-list mailing list