# comparing values in two sets

Tim Chase python.list at tim.thechases.com
Mon May 15 02:19:33 CEST 2006

```> I'd like to compare the values in two different sets to
> test if any of the positions in either set share the same
> value (e.g., if the third element of each set is an 'a',
> then the test fails).

There's an inherant problem with this...sets by definition
are unordered, much like dictionaries.  To compare them my
such means, you'd have to convert them to lists, sort the
lists by some ordering, and then compare the results.
Something like

s1 = set([1,3,5,7,9])
s2 = set([1,2,3])
list1 = list(s1)
list2 = list(s2)
list1.sort()
list2.sort()

if [(x,y) for x,y in zip(list1,list2) if x == y]:
print "There's an overlap"
else:
print "No matching elements"

Just to evidence matters, on my version of python (2.3.5 on
Debian), the following came back:

>>> set([1,3,5,7,9])
set([1,3,9,5,7])

That's not the original order, but the definition of a set
isn't hurt/changed by any ordering.

Thus, asking for the "position in a set" is an undefined
operation.

-tkc

PS:  for the above was done in 2.3.5 using this line:
from sets import Set as set

```

More information about the Python-list mailing list