python – group lists within list together given they have at least one common element


I am grouping lists within list together given they have one element in common.

My input data is

((1, 2), (3, 4), (5, 6), (1, 2, 7), (8, 2), (9, 5))

My output is:

((1, 2), (1, 2, 7), (8, 2), (3, 4), (5, 6), (9, 5))

The code I am using to accomplish this is:

mylist = ((1, 2), (3, 4), (5, 6), (1, 2, 7), (8, 2), (9, 5))
temp_result = list()

for i in range(len(mylist)):
    temp_result.append(mylist(i))
    for j in range(i + 1, len(mylist)):
        if (set(mylist(i)) & set(mylist(j))):
            temp_result.append(mylist(j))

result = ()
for elem in temp_result:
    if elem not in result:
        result.append(elem)

print(result)

However, something tells me that this code can be improved a lot. Can someone please help me out?