Python: Join lists of lists by the first element
Question: I'm trying to combine a list of lists/tuples by the first element in the list
- something like this:

Input:

    
    
    [(1, [32, 432, 54]), (1, [43, 54, 65]), (2, [2, 43, 54]), (2, [1, 5, 6])]
    

Output:

    
    
    [(1, [32, 432, 54], [43, 54, 65]), (2, [2, 43, 54], [1, 5, 6])]
    

The lists are actually ordered by the first element like in my example input,
and it doesn't matter if at the end the tuples are lists.

Is there an efficient/pythonic way to do this?


Answer: Using
[`itertools.groupby`](https://docs.python.org/2/library/itertools.html#itertools.groupby)
and [list
comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-
comprehensions):

    
    
    >>> lst = [(1, [32, 432, 54]), (1, [43, 54, 65]), (2, [2, 43, 54]), (2, [1, 5, 6])]
    >>> import itertools
    >>> [(key,) + tuple(v for k, v in grp)
    ...     for key, grp in itertools.groupby(lst, key=lambda x: x[0])]
    [(1, [32, 432, 54], [43, 54, 65]), (2, [2, 43, 54], [1, 5, 6])]
    

