Getting some element from sets.Set

Christopher Arndt chris.arndt at web.de
Mon May 7 09:56:22 EDT 2007


On 4 Mai, 10:23, "jm.sur... at no.spam.gmail.com" <jm.sur... at 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.
>
> In the particular case, I have to read an attribute from any one of
> the elements, which one doesn't matter because this attribute value is
> same across all elements in the set.

Just to clarify: do you want to just get an *arbitrary* element from
the set or do you want to find a *specific* element in the set?

In the first case you have to convert it to a list (as pointed out
earlier in this thread):

>>> s = set(range(10))
>>> list(s)[0]
0

In the second case, just use th "in" operator:

>>> 10 in s
False
>>> 5 in s
True

Since you have to have a reference to the object for whose membership
you are testing, you can just use this object.

Stupid example:

>>> class Point:
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
...
>>> l = [Point(n,n+2) for n in range(10)]
>>> s = set(l)
>>> Point(0,2) in s
False
>>> l[0] in s
True
>>>
>>> l[0].x,l[0].y
(0, 2)


Chris




More information about the Python-list mailing list