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

Fredrik Lundh fredrik at
Wed Jan 25 16:39:03 CET 2006

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

you can make this a bit more obvious:

    >>> [item] = s

this is almost twice as fast as the fastest alternative from my previous


More information about the Python-list mailing list