Search code examples
pythoncombinationspython-itertoolscombinatorics

Every permutation of list elements (without replacement)


In Python 2.7 I'd like to get the self-cartesian product of the elements of a list, but without an element being paired with itself.

 In[]: foo = ['a', 'b', 'c']
 In[]: [x for x in itertools.something(foo)]
Out[]: 
       [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

Currently I do:

[x for x in itertools.product(foo, repeat=2) if x[0] != x[1]]

but I suspect there's a built-in method for this. What is it?

Note: itertools.combinations wouldn't give me ('a', 'b') and ('b', 'a')


Solution

  • You are looking for permutations instead of combinations.

    from itertools import permutations
    
    foo = ['a', 'b', 'c']
    print(list(permutations(foo, 2)))
    
    # Out: [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]