Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 881
LondonRob Avatar asked Dec 24 '22 14:12

LondonRob


1 Answers

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')]
like image 164
Delgan Avatar answered Jan 13 '23 11:01

Delgan