4

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')

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
LondonRob
  • 73,083
  • 37
  • 144
  • 201

1 Answers1

10

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')]
Delgan
  • 18,571
  • 11
  • 90
  • 141
  • 2
    The documentation neatly corroborates this by showing that `permutations()` can be implemented in terms of `product()` with repeats removed, exactly what the OP is doing. – Martijn Pieters Sep 08 '15 at 11:05