Question: My function is currently returning:

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

```

However, I need the final output to be:

```
[('a', 'h'), ('d', 'g')]

```

As you can see, if i[1] and i[2] match I need i[0] to be paired together. 

I was trying to use a for loop but I can't think of how to write it, at this moment.

Answer: 
This seems to work:

```
from itertools import combinations

l = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'e', 'f'), ('h', 'b', 'c')]
print([(a[0], b[0]) for a, b in combinations(l, 2) if a[1:] == b[1:]])

```
You can do this by sorting the list based on second and third element , and then using [`itertools.groupby`](https://docs.python.org/2/library/itertools.html#itertools.groupby) . Then for each group, you can take the first elements from the elements inside it. Example -

```
>>> a = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'e', 'f'), ('h', 'b', 'c')]
>>> lst = []
>>> new_a = sorted(a, key=lambda i: (i[1], i[2]))
>>> for _, x in itertools.groupby(new_a, lambda i: (i[1], i[2])):
...     lst.append(tuple(y[0] for y in x))
...
>>> lst
[('a', 'h'), ('d', 'g')]

```

---

This can also be done in one line as (though unreadable) - 

```
>>> l = [tuple(y[0] for y in x) for _, x in itertools.groupby(sorted(a, key=lambda i: (i[1], i[2])), lambda i: (i[1], i[2]))]
>>> l
[('a', 'h'), ('d', 'g')]

```