Making Combinations (Python)
Question: In Python, is there a better way to get the set of combinations of n elements
from a k-element set than nested for loops or list comprehensions?

For example, say from the set [1,2,3,4,5,6] I want to get
[(1,2),(1,3),(1,4),(1,5),(1,6),(2,3),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6),(4,5),(4,6),(5,6)].
Is there a better of of making it than

    
    
    nums=[1,2,3,4,5,6]
    doubles=[]
    for a in nums:
        for b in nums[a+1:]
            doubles.append((a,b))
    

? It's okay if the elements of the list we end up with are sets, tuples, or
lists; I just feel there should be an easier way to do this.


Answer: The [`itertools`](http://docs.python.org/2/library/itertools.html) module has
a lot of really powerful tools that can be used in situations like this. In
this case, you want
[`itertools.combinations`](http://docs.python.org/2/library/itertools.html#itertools.combinations).
Some other ones that you might find useful are
[`itertools.combinations_with_replacement`](http://docs.python.org/2/library/itertools.html#itertools.combinations_with_replacement)
and
[`itertools.permutations`](http://docs.python.org/2/library/itertools.html#itertools.permutations).

Example:

    
    
    >>> import itertools
    >>> list(itertools.combinations(range(1,7),2))
    [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
    >>> list(itertools.combinations_with_replacement(range(1,7),2))
    [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 3), (3, 4), (3, 5), (3, 6), (4, 4), (4, 5), (4, 6), (5, 5), (5, 6), (6, 6)]
    >>> list(itertools.permutations(range(1,7),2))
    [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5)]
    

