Getting some element from sets.Set

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Fri May 4 02:40:35 EDT 2007


On Thu, 03 May 2007 23:08:33 -0700, jm.suresh at no.spam.gmail.com wrote:

> It is not possible to index set objects. That is OK.
> But, what if I want to find some element from the Set.
> 
> from sets import Set
> s = Set( range(12 )
> 
> if I do pop, that particular element gets removed.
> I do not want to remove the element, but get some element
>  from the Set.
> 
> s.some_element() # Is not available

Looking at help(sets.Set), it seems that there is no direct way to ask for
a single element of a set, except with pop. So you can pop an element,
then add it back in:

some_element = s.pop()
s.add(some_element)

Another solution is to extract all the elements, then pick one:

some_element = list(s)[0]


-- 
Steven D'Aprano 




More information about the Python-list mailing list