0

I have a list

a = ['a', 'b', 'c']

How I can get all combinations with repeat and without them from this list. Final output will be:

[('a', 'b', 'c'),
 ('a', 'c', 'b'),
 ('b', 'a', 'c'),
 ('b', 'c', 'a'),
 ('c', 'a', 'b'),
 ('c', 'b', 'a')]
itdxer
  • 1,236
  • 1
  • 12
  • 40

2 Answers2

4

Using itertools.permutations:

>>> import itertools
>>> a = ['a', 'b', 'c']
>>> list(itertools.permutations(a))
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

use permutations function from itertools

from itertools import permutations
x = list(itertools.permutations(a))

The above list will not be lexicographically sorted. If the given input list is sorted, then the output list will be sorted. Else you have to manually sort the list using x.sort()

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69