# Set operations on object attributes question

Raymond Hettinger python at rcn.com
Tue Oct 23 17:39:30 CEST 2007

```[Duane]
> LoTuples1 = [(1,1,0),(1,2,1),(1,3,3)]
> Set1=set(LoTuples1)
> LoTuples2 = [(2,1,3),(2,2,4),(2,3,2)]
> Set2=set(LoTuples2)
>
> What I would like to be able to do is:
>
> Set3 = Set1union(Set2)
> Set3.intersection(Set2, <use object[2]>)
>
> to return:
> set([(2,1,3), (1,3,3)])
>
> How can one do this operation?

Conceptually, there is more than one operation going on. First,
finding the attributes shared in both sets:
ca = set(t[2] for t in LoTuples1) & set(t[2] for t in LoTuples2)
which gives:
set([3])

Second, find any tuple which has that attribute (including multiple
results for the same attribute):
set(t for t in (LoTuples1 + LoTuples2) if t[2] in ca)
which returns:
set([(2, 1, 3), (1, 3, 3)])

Wanting multiple results for the same attribute value (i.e. both
(2,1,3) and (1,3,3) have 3 in the second position) is why multiple
steps are needed; otherwise, the behavior of intersection() is to
return a single representative of the equivalence class.

Raymond

```