I have a "combination" problem to find a cluster of different keys for which I try to find a optimized solution:

I have this list of list "l":

```
l = [[1, 5],
 [5, 7],
 [4, 9],
 [7, 9],
 [50, 90],
 [100, 200],
 [90, 100],
 [2, 90],
 [7, 50],
 [9, 21],
 [5, 10],
 [8, 17],
 [11, 15],
 [3, 11]]

```

every Id is linked to another id but could possibly be linked to another key - through another key - (see picture below). The goal would be to find all the keys that belong to the same cluster in an optimized way  

[![enter image description here](https://i.stack.imgur.com/QEFpH.png)](https://i.stack.imgur.com/QEFpH.png)

The result wanted is :

```
[{1, 2, 4, 5, 7, 9, 10, 21, 50, 90, 100, 200}, {8, 17}, {3, 11, 15}]

```

The code I currently have is:

```
out = []

while len(l)>0:
    first, *rest = l
    first = set(first)

    lf = -1
    while len(first)>lf:
        lf = len(first)
        print(lf)
        rest2 = []
        for r in rest:
            if len(first.intersection(set(r)))>0:
                first |= set(r)
            else:
                rest2.append(r)     
        rest = rest2

    out.append(first)
    l = rest

```

And I get the result previously showed. The problem comes when using it on 2 million of lines where it takes ages to run.

Is there any other way to solve this problem in an optimized way ?