Get item from set

Terry Reedy tjreedy at
Mon Apr 27 20:48:25 CEST 2009

Johannes Bauer wrote:
> Hi group,
> I have a very simple about sets. This is a minimal example:
> #!/usr/bin/python
> class x():
> 	def __init__(self, y):
> 		self.__y = y
> 	def __eq__(self, other):
> 		return self.__y == other.__y
> 	def __hash__(self):
> 		return hash(self.__y)
> a = x("foo")
> s = set([x("bar"), x("moo"), a])
> z = x("foo")
> print("z = ", z)
> print(s)
> for i in s:
> 	print(i, i == a, i is a, i == z, i is z)
> The problem is: two instances of x() are equal (__eq__ returns true),
> but they are not identical. I have an equal element ("z"), but want to
> get the *actual* element ("a") in the set. I.d. in the above example,
> i'd like something like:
> print(s.getelement(z) is a)
> True
> Is there something like the "getelement" function? How can I do what I want?

No. but you pratically wrote it: in your code, when i == z, then i is 
the element you want.

def getelement(sset, item):
   for i in sset:
     if i == item: return i

The only use for this is see, though, is getting the representative of 
an equivalence class from any member thereof.


More information about the Python-list mailing list