This will produce the result you are describing. It should work better than n * n if you don't have intersections, but otherwise it should benefit some.
mysets = [set([0, 1, 2]), set([3, 2]), set([4, 1]), set([5, 6]), set([7, 8])] # Require at least one set in the output. output = [mysets.pop(0)] while mysets: test = mysets.pop(0) for idx, other in enumerate(output): if test & other: output[idx] |= test break else: output.append(test) # output -> [set([0, 1, 2, 3, 4]), set([5, 6]), set([8, 7])]
source share