-3

For example,

list = [0, 1, 2]

I want a list of all possible 2-combinations:

combinations = [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]

It seems to me that all the tools in itertools in Python only make one of (1,0) and (0,1), not both, I need both. Any suggestions, other than entering them by hand?

Georgy
  • 9,972
  • 7
  • 57
  • 66
Investor
  • 185
  • 7
  • VTR since the [linked duplicate](/questions/533905/get-the-cartesian-product-of-a-series-of-lists) doesn't cover the `repeat` parameter and so doesn't help with getting the product of a list with itself. – wjandrea Aug 21 '21 at 03:54

2 Answers2

3

You are looking for a Cartesian product of that list with itself, not a permutation nor a combination. Therefore you should use itertools.product with repeat=2:

from itertools import product

li = [0, 1, 2]
print(list(product(li, repeat=2)))
>> [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
DeepSpace
  • 72,713
  • 11
  • 96
  • 140
0

Can be done by importing itertools:

import itertools

list1 = [0, 1, 2]
print(list(itertools.product(list1,repeat=2)))

Output:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Resource: You can learn more about it - here

Taufiq Rahman
  • 5,436
  • 2
  • 35
  • 43