0

I have a list of even N elements and would like to get a list of lists of all possible and unique pairs, e.g.:

list = [1, 2, 3, 4, 5, 6]
result: [[(1,2), (3,4), (5,6)], [(1,2), (3,5), (4,6)] ...

So each list I get as the result should have N/2 elements (pairs with unique numbers). This question seemed similar to my problem, although the answer gives the lists with 2 combinations only and it doesn't work for N > 4; not sure if it's possible to rework this solution for my purposes.

I suppose that one possible option is to:

  1. iterate through each possible order of N numbers (123456, 123465 ... 654321)
  2. create a list of pairs for each following 2 elements ([1,2,3,4,5,6] -> [(12), (34), (56)])
  3. sort those pairs and eliminate duplicates

But it feels that there should be a more elegant solution, would be grateful for help :)

  • FYI don't use the variable name `list` as it is already pre-defined by Python and could cause errors down the road. – Michael S. Aug 22 '22 at 15:39
  • 2
    Look at the `itertools` module... – MattDMo Aug 22 '22 at 15:40
  • I think you might really be looking for unique *partitions* of your list into pairs. That's a fairly hard problem in a general sense (partitions of list length `n` into subsets size `m`), but if you're always looking at short lists like your sample (low n and m), you can do it very fast. Is that what you're after? – J Richard Snape Aug 22 '22 at 16:10

1 Answers1

1

Unless I'm mistaken,

l = [1, 2, 3, 4, 5, 6]

x = list(itertools.combinations(itertools.combinations(l, 2), 3))

does what you want.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • Thanks, although I believe that's not the case. The result of this code starts with: "((1, 2), (1, 3), (1, 4))" And what I need is sets of (in this case - set of 3) pairs in which every element is unique (so in every set, all N numbers are used). – Krzysztof Sieja Aug 22 '22 at 15:51
  • 2
    @KrzysztofSieja, try `[[p[i: i + 2] for i in range(0, len(p), 2)] for p in permutations(l)]` – Olvin Roght Aug 22 '22 at 15:51