Shivkumar kondi
Shivkumar kondi

Reputation: 6762

How to get single unique permutation entry from list

I have this list after permutation:

import itertools
print list(itertools.permutations([1,2,3,4], 2))

Here's the output :

[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]

In that list we can find replicated elements like (1,2) - (2,1) and (1,3) - (3,1) and so ..

What I want is to get only one replicate element from this list, output list like:

[(1, 2),(1, 3),(1, 4),(2, 3),(2, 4),(3, 4)]

Thanks in advance

Upvotes: 1

Views: 152

Answers (1)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48092

You need the combinations of the list, and not the permutations. For that there is itertools.combinations() function in Python:

>>> from itertools import combinations
>>> l = [1,2,3,4]
>>> list(combinations(l, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

As per the document:

  • Permutations are for lists (order matters)

  • Combinations are for groups (order doesn’t matter).

Upvotes: 4

Related Questions