Python create many-to-many relationships from a list
Question: I have a list, say `terms = ['A', 'B', 'C', 'D']`

Which is the best way to create a list-of-lists or list-of-tuples of many-to-
many relationships like this;

    
    
    [['A','B'],['A','C'],['A','D'],['B','C'],['B','D'],['C','D']]
    


Answer: Using
[`itertools.combinations()`](http://docs.python.org/2/library/itertools.html#itertools.combinations):

    
    
    from itertools import combinations
    
    list(combinations(terms, r=2))
    

Demo:

    
    
    >>> from itertools import combinations
    >>> terms = ['A', 'B', 'C', 'D']
    >>> list(combinations(terms, r=2))
    [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
    

These are tuples, not lists, but that's easily remedied if that is a problem:

    
    
    >>> map(list, combinations(terms, r=2))
    [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]
    

