0

I would like to find all combinations of my list of numbers without the pair being the same. The code I've written below gives me all combinations. So, I also get [1, 1], [2, 2] and [3, 3], which I'd like to remove.

nr_list = [1, 2, 3]
combinations = []
for a in nr_list:
    for b in nr_list:
        pair = [a, b]
        combinations.append(pair)
print(combinations)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Vic
  • 37
  • 4
  • 2
    Look at [`itertools.combinations`](https://docs.python.org/3/library/itertools.html#itertools.combinations) – buran Oct 23 '21 at 18:29
  • 2
    you may add a line of condition inside the loop likewise `if a!=b:` – hakanerdem Oct 23 '21 at 18:30
  • 2
    Does this answer your question? [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – buran Oct 23 '21 at 18:30

3 Answers3

2
from itertools import permutations

nr_list = [1, 2, 3]
print(list(permutations(nr_list, 2)))
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

Similar question: link

andrey.s
  • 121
  • 5
1

Just don't append the pair to the combinations if the items in pair are equal ie if pair[0] != pair[1]:

hopperelec
  • 133
  • 1
  • 2
  • 13
0

Try this code

nr_list = [1, 2, 3]
combinations = []
for a in nr_list:
    for b in nr_list:
        if(a!=b):
            pair = [a, b]
            combinations.append(pair)
print(combinations)

Akash Kumar
  • 307
  • 1
  • 4
  • 9
  • 1
    Don't just send the code of the fix, tell people the problem and what they can do to make what they want so they don't depend on always asking. – Gvinfinity Oct 23 '21 at 18:32