1

I would like to get all combinations of a list:

L = ["a","b","c"]
combinations(L,length=2)
# [("a","a"),("a","b"),("a","c"),("b","a"),("b","b"),("b","c"),("c","a"),("c","b"),("c","c")]

I've tried

itertools.combinations()

but this returned

[('a', 'b'), ('a', 'c'), ('b', 'c')]

When I use itertools.permutations(), it just returns the combinations with the length of the iteration, which is also not what I want.

Any librarys / function that I can use, without writing my own?

CMinusMinus
  • 426
  • 1
  • 3
  • 11
  • You mean `permutations` not `combinations`. Try that function instead. – michalwa Jun 27 '20 at 13:26
  • Does this answer your question? [Get all combination with n -length from a list](https://stackoverflow.com/questions/24536725/get-all-combination-with-n-length-from-a-list) – ywbaek Jun 27 '20 at 13:37

5 Answers5

4

You can use itertools.product with repeat=2 like so:

from itertools import product

L = ["a","b","c"]
print(list(product(L, repeat=2)))
#[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
Anwarvic
  • 12,156
  • 4
  • 49
  • 69
3

A simple list comprehesion can do the job too.

L = ["a","b","c"]
print([(a,b) for a in L for b in L])
#[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
Koralp Catalsakal
  • 1,114
  • 8
  • 11
2

itertools module has a function called product which is what you are looking for.

>>> L = ["a", "b", "c"]
>>> list(itertools.product(L, repeat=2))
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
taha
  • 722
  • 7
  • 15
2

The product function from itertools offers a solution.

In [17]: from itertools import product

In [18]: L = ["a","b","c"]

In [19]: list(product(L, L))
Out[19]:
[('a', 'a'),
 ('a', 'b'),
 ('a', 'c'),
 ('b', 'a'),
 ('b', 'b'),
 ('b', 'c'),
 ('c', 'a'),
 ('c', 'b'),
 ('c', 'c')]
navneethc
  • 1,234
  • 8
  • 17
1

You can use the second parameter of itertools.permutations():

from itertools import permutations

L = ["a","b","c"]

print([n for n in permutations(L,2)]+[(i,i) for i in L])

Output:

[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('a', 'a'), ('b', 'b'), ('c', 'c')]

From the documentation:

itertools.permutations(iterable, r=None)

Return successive r length permutations of elements in the iterable. If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.

Red
  • 26,798
  • 7
  • 36
  • 58