[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('f', 'g')]

def consolidate(sets):
    setlist = [s for s in sets if s]
for i, s1 in enumerate(setlist):
    if s1:
        for s2 in setlist[i + 1:]:
            intersection = s1.intersection(s2)
if intersection:
    s2.update(s1)
s1.clear()
s1 = s2
return [s for s in setlist if s]
print(consolidate([set(pair) for pair in pairs]))
How to aggregate matching pairs into "connected components" in Python